<?php

/**

 * 计划管理
 * 
 * @access  public 
 * @author  zhangyingheng<zhang_yh@jsumt.com.cn> 
 */

namespace Home\Controller;

use Think\Controller;

class FlowController extends BaseController {

    public function _initialize() {
        parent::_initialize();
        $this->limit = 10;

        //获取流程分类
        $flowTypes = M('flow_sort')->where('sort_no != 0')->select();
        $this->flowTypes = $flowTypes;

        $this->webid = M('web')->where('webname="流程审批"')->getField('id');
    }

    public function index() {
        //获取常用流程
        $flows = M('flow_type')->field('flow_id,flow_name,form_id,flow_sort,icon,color')->where('is_show = 1 and is_delete = 0')->order('flow_no')->select();

        $this->flows = $flows;
        $this->display();
    }

    //展示流程设计图
    public function design() {
        $flow_id = I('flow_id');
        $prcs_id = I('prcs_id');
        $this->flow_id = $flow_id;
        $this->prcs_id = $prcs_id;

        $this->display();
    }

    public function getFlowDesign() {
        $flow_id = I('flow_id');

        $map['flow_id'] = I('flow_id');
        if (I('prcs_id') > 1) {
            $map['prcs_id'] = array('elt', I('prcs_id'));
        }
        $prcs_max = M('flow_process')->where('flow_id=' . $flow_id)->max('prcs_id');

        $data = M('flow_process')->where($map)->order('PRCS_ID')->select();
        $top_auto = 20;
        $left_auto = 20;
        $prcs_count = 0;

        foreach ($data as $key => $row) {
            $data[$key]['prcs_name'] = iconv('GB2312', 'UTF-8', $row['prcs_name']);
            $data[$key]['prcs_in'] = iconv('GB2312', 'UTF-8', $row["prcs_in"]);
            $data[$key]['prcs_out'] = iconv('GB2312', 'UTF-8', $row["prcs_out"]);
            $data[$key]['prcs_in_set'] = iconv('GB2312', 'UTF-8', $row["prcs_in_set"]);
            $data[$key]['prcs_out_set'] = iconv('GB2312', 'UTF-8', $row["prcs_out_set"]);
            $data[$key]['prcs_in'] = str_replace("'include'", _("'包含'"), $data[$key]['prcs_in']);
            $data[$key]['prcs_in'] = str_replace("'exclude'", _("'不包含'"), $data[$key]['prcs_in']);
            $row["prcs_out"] = str_replace("'include'", _("'包含'"), $row["prcs_out"]);
            $row["prcs_out"] = str_replace("'exclude'", _("'不包含'"), $row["prcs_out"]);

            $prcs_to = $row["prcs_to"];
            if ($prcs_to == '') {
                if ($row['prcs_id'] != $prcs_max) {
                    $prcs_to = $row['prcs_id'] + 1;
                } else {
                    $prcs_to = $prcs_max;
                }
            }

            $set_left = $row["set_left"];
            $set_top = $row["set_top"];

            if ($set_left == 0) {
                $set_left = $left_auto;
            }

            if ($set_top == 0) {
                $set_top = $top_auto;
            }

            if (($row['prcs_id'] % 2) == 0) {
                $left_auto += 180;
                $top_auto = 20;
            } else {
                $top_auto = 200;
            }

            $prcs_to_title = $prcs_to;
            $prcs_to_title = str_replace(",0", "," . _("结束"), $prcs_to_title);

            if (($prcs_to_title != "") && (substr($prcs_to_title, 0, 1) == "0")) {
                $prcs_to_title = _("结束") . substr($prcs_to_title, 1);
            }
            $prcs_to_title = _("·下一步骤：") . $prcs_to_title;

            if ($row['prcs_type'] == 1) {
                $row['prcs_type'] = "child";
            } else if ($row['prcs_type'] == 2) {
                $row['prcs_type'] = "out";
            } else if ($row['prcs_id'] == 1) {
                $row['prcs_type'] = "start";
            } else {
                if (find_id($prcs_to, "0") || ($prcs_to == $prcs_max + 1)) {
                    $row['prcs_type'] = "end";
                } else {
                    $row['prcs_type'] = "general";
                }
            }

            $prcs_content = "<b>" . $row['prcs_id'] . "</b><br>" . $row['prcs_name'];

            if ($row['child_flow'] != 0) {
                $prcs_content .= _("(子流程)");
            }

            if ($row['prcs_in']) {
                $condition = '转入条件：' . $row['prcs_in'];
            } elseif ($row['prcs_out']) {
                $condition = '转出条件：' . $row['prcs_out'];
            }
//            $condition = $row['prcs_in'] ? '转入条件：'.$row['prcs_in'] : '转出条件：'.$row['prcs_out'];

            $title = $prcs_to_title . '<br/>' . $condition . '<hr>';
            $prcs_array["list"][] = array("id" => $row['id'], "prcs_id" => $row['prcs_id'], "title" => $title, "prcs_content" => $prcs_content, "left" => $set_left, "top" => $set_top, "prcs_type" => $row['prcs_type'], "to" => $prcs_to);
        }

        //获取流程信息
        $prcs_array['flow_name'] = M('flow_type')->where('flow_id=' . $flow_id)->getField('flow_name');
        $prcs_array['flow_sort'] = getFlowSortName($flow_id);

        $prcs_array["total"] = count($data);
//        print_r($prcs_array);die;
        $this->ajaxReturn($prcs_array);
    }

    public function pageNum($flag, $where = '') {
        if ($flag) {
            switch ($flag) {
                case 1: //未办结
                    $map['prcs_flag'] = array('in', [1, 2]);
                    break;
                case 2:     //已办结
                    $map['prcs_flag'] = array('in', [3, 4]);
                    break;
            }
            $map['user_id'] = session('user_id');

            //取所有和我相关的run_id
            $ids = M('flow_run_prcs')->where($map)->getField('run_id', true);
            if (!is_array($ids)) {
                $ids[] = $ids;
            }
        } else {
            $map['user_id'] = session('user_id');
            //取所有和我相关的run_id
            $ids = M('flow_run_prcs')->where($map)->getField('run_id', true);
            if (!is_array($ids)) {
                $ids[] = $ids;
            }
        }
        $rMap['run_id'] = array('in', $ids);
        $rMap['del_flag'] = 0;

        if ($where) {
            $rMap['_complex'] = $where;
        }
//        print_r($rMap);
        $count = M('flow_run')->where($rMap)->count();
        return $count;
    }

    public function lists() {
        $flag = I('type');
        $limit = 15;

        $hasPriv = true;
        if (isset($_GET['type'])) {
            if (I('type') == 3) {
                //根据用户流程查询权限查询
                $flowIds = getUserFlowPriv(1);
                if (!empty($flowIds)) {
                    $where['flow_id'] = array('in', $flowIds);
                }

//                print_r($flowIds);
                if (isset($_GET['flowId']) && I('flowId')) {
                    if (!hasFlowPriv($flowIds, I('flowId'))) {
                        $hasPriv = false;
                    }
                    $where['flow_id'] = I('flowId');
                    $this->flowId = I('flowId');
                }

                if (isset($_GET['runName']) && I('runName')) {
                    //如果流程名存在的话，取run_ids
                    $where['run_name'] = array('like', '%' . I('runName') . '%');
                    $ids = M('flow_run')->where(array('run_name' => array('like', '%' . I('runName') . '%')))->getField('flow_id');
                    if (!hasFlowPriv($flowIds, $ids)) {
                        $hasPriv = false;
                    }
                    $this->runName = I('runName');
                }
                if (isset($_GET['start']) && I('start')) {
                    $start = I('start');
                    $end = I('end') ? I('end') : date('Y-m-d H:i:s');
                    $where['BEGIN_TIME'] = array('between', [$start, $end]);
                    $this->start = $start;
                    $this->end = $end;
                }
                if (isset($_GET['runId']) && I('runId')) {
                    $where['run_id'] = I('runId');
                    $ids = M('flow_run')->where('run_id=' . I('runId'))->getField('flow_id', true);
                    if (!hasFlowPriv($flowIds, $ids)) {
                        $hasPriv = false;
                    }
                    $this->runId = I('runId');  //流水号
                }
                if (isset($_GET['range']) && I('range') >= 0) {
                    if (I('range') == 1) {
                        //指定发起人
                        $where['begin_user'] = I('user_ids')[0];
                    }
                    if (I('range') == 2) {
                        //指定经办人
                        $runMap['flow_prcs'] = array('neq', 1);
                        $runMap['user_id'] = I('user_ids')[0];
                        $runIds = M('flow_run_prcs')->field('run_id,prcs_id,prcs_flag')->where($runMap)->getField('run_id', true);
                        if (!is_array($runIds)) {
                            $runIds[] = $runIds;
                        }
                        foreach ($runIds as $key => $row) {
                            $ids[$row['run_id']] = $row;
                        }
                        if ($ids) {
                            $where['run_id'] = array('in', $ids);
                        }
                    }
                    $this->range = I('range');
                    $this->userId = I('user_ids')[0];
                    $this->userName = getChineseName(I('user_ids')[0]);
                }
                if (isset($_GET['prcsFlag']) && I('prcsFlag') >= 0) {
//                    $type = I('prcsFlag');
                    $this->prcsFlag = I('prcsFlag');
                    $where['end_time'] = I('prcsFlag') == 2 ? array('neq', '') : array('exp', 'is null');
                } else {
                    $type = '';
                }
            } else {
                if (isset($_GET['runName']) && I('runName')) {
                    //如果流程名存在的话，取run_ids
                    $where['run_name'] = array('like', '%' . I('runName') . '%');
                    $this->runName = I('runName');
                }
                if (isset($_GET['start']) && I('start')) {
                    $start = I('start');
                    $end = I('end') ? I('end') : date('Y-m-d');
                    $where['begin_time'] = array('between', [$start, $end]);
                    $this->start = $start;
                    $this->end = $end;
                }
            }
        }
//print_r($where);
        $runs = $this->getLists($flag, $limit, '', $where);
        $num = $this->pageNum($flag, $where);
        $this->page = $this->pageLists($num, $limit);
        //$runs[0]['begin_user'] = getChineseName($runs[0]['begin_user']);
//        print_r($runs);
        //根据prcsFlag状态，重组数组
        if (isset($_GET['prcsFlag']) && I('prcsFlag') == 1) {
            $tmp = $runs;
            $runs = [];
            foreach ($tmp as $key => $row) {
                if ($row['flow_run_prcs'] && $row['flowCurrStatus'] != 4) {
                    //进行中
                    $runs[] = $row;
                }
            }
        } else if (I('prcsFlag') == 2) {
            $tmp = $runs;
            $runs = [];
            foreach ($tmp as $key => $row) {
                if ($row['flow_run_prcs'] && $row['flowCurrStatus'] == 4) {
                    //进行中
                    $runs[] = $row;
                }
            }
        }

        $this->flowCates = $this->getFlowSort();
//        print_r($this->flowCates);
        $this->runs = $runs;
        $this->flag = $flag;
        $this->date = date('Y-m-d');
        $this->hasPriv = $hasPriv;
        $this->display();
    }

    //按分类获取子流程
    public function getFlowType() {
        $id = I('id');

        //通过部门\角色\用户获取相关流程
        //获取所有流程的第一步
        $firstSteps = M('flow_process')->field('flow_id,prcs_id,prcs_dept,prcs_priv,prcs_user')->where('prcs_id=1')->select();
        $newData = array();
        foreach ($firstSteps as $key => $row) {
            if (($row['prcs_dept'] == 'ALL_DEPT' || $row['prcs_dept'] == '') && ($row['prcs_priv'] == '') && ($row['prcs_user'] == '') || (strpos($row['prcs_dept'], session('dept_id')) !== false) || (strpos($row['prcs_priv'], session('user_priv')) !== false) || (strpos($row['prcs_user'], session('user_id')) !== false)) {
                $newData[] = $row;
                $flow_ids[] = $row['flow_id'];
            }
        }
        $map['flow_id'] = array('in', $flow_ids);
        $map['flow_sort'] = $id;
        $map['icon'] = array('neq', '');
        $map['is_delete'] = 0;
        $data = M('flow_type')->field('flow_id,flow_name,form_id,flow_sort,icon,color')->where($map)->order('flow_no')->select();
        $this->ajaxReturn($data);
    }

    //表单页面 添加和修改
    public function form() {
        if (IS_AJAX) {
            $data = I('post.');
            $type = I('get.type');

            //如果run_id存在，修改表单
            if (I('run_id')) {
                unset($data['run_id']);
                $flow_id = M('flow_run')->where('run_id=' . I('run_id'))->getField('flow_id');
                $table = 'flow_data_' . $flow_id;
                foreach ($data as $key => $row) {
                    if (substr($key, 0, 4) == 'DATA') {
                        $saveData[strtolower($key)] = $row;
                    }
                }
                if (I('user_ids')) {
                    $saveData['users'] = implode(',', I('user_ids'));
                }
                $saveRes = M($table)->where('run_id=' . I('run_id'))->save($saveData);

                //如果uploads存在，修改附件
                if ($data['uploads']) {
                    $runData['uploads'] = $data['uploads'];
                    $runData['uploads_url'] = $data['uploads_url'];
                    $runMap['run_id'] = I('run_id');
                    $runRes = M('flow_run')->where($runMap)->save($runData);
                }

                $flag = true;
                if ($data['feedback'] == '') {
                    if ($data['prcs_id'] == 1) {
                        $flag = true;
                    } else {
                        //判断当前用户会签条件  update zyh 2018/7/24
                        $feedback = $process['feedback'];
                        unset($map);
                        $map['run_id'] = I('run_id');
                        $map['prcs_id'] = $data['prcs_id'];
                        $map['user_id'] = session('user_id');
                        $count = M('flow_run_feedback')->where($map)->count();

                        $pmap['flow_id'] = I('flow_id');
                        $pmap['prcs_id'] = $data['prcs_id'];
                        $process = M('flow_process')->where($pmap)->find();
                        if ($feedback == 2 || ($feedback == 0 && strpos($process['prcs_out'], 'USER_SIGN') !== false)) {
                            //强制会签或允许会签状态下会签意见不为空时
                            $flag = $count ? true : false;
                        } else {
                            $flag = true;
                        }
                    }
                } else {
                    //防止重复提交
                    unset($map);
                    $map['run_id'] = I('run_id');
                    $map['prcs_id'] = $data['prcs_id'];
                    $map['user_id'] = session('user_id');
                    $feedCount = M('flow_run_feedback')->where($map)->count();
                    if (!$feedCount) {
                        //添加会签意见
                        $fData['run_id'] = I('run_id');
                        $fData['prcs_id'] = $data['prcs_id'];
                        $fData['flow_prcs'] = $data['prcs_id']; //升级后增加的字段，不知道有什么用，暂时和prcs_id一样
                        $fData['user_id'] = session('user_id');
                        $fData['content'] = $data['feedback'];
                        $fData['edit_time'] = date('Y-m-d H:i:s');
                        $res = M('flow_run_feedback')->add($fData);
                    }
                }
                // var_dump($flag);die;
                if ($flag) {
                    if ($saveRes !== false || $res !== false) {
                        if ($type == 1) {
                            $return['info'] = '修改成功';
                            if (I('flowType')) {
                                $return['reload'] = 1;
                            } else {
                                $return['url'] = U('Flow/lists');
                            }
                        } else if ($type == 2) {
                            //取当前用户步骤信息
                            unset($map);
                            $map['run_id'] = I('run_id');
                            $map['flow_prcs'] = $data['prcs_id'];
                            $map['user_id'] = session('user_id');
                            $row = M('flow_run_prcs')->where($map)->find();

                            //判断是否为无主办人会签
                            $default = $process['top_default'];

                            //如果是无主办人会签的话，改当前用户状态为4,如果是有主办人会签，改状态为2，加完成时间
                            $smap['run_id'] = I('run_id');
                            $smap['flow_prcs'] = $data['prcs_id'];
                            $smap['user_id'] = session('user_id');
                            if ($row['op_flag']) {
                                $sData['prcs_flag'] = 2;    //主办人点击办理完毕时不改状态
                            } else {
                                $sData['prcs_flag'] = 4;    //经办人点击办理完毕时状态改为4
                            }

                            $sData['deliver_time'] = date('Y-m-d H:i:s');
                            M('flow_run_prcs')->where($smap)->save($sData);

                            //判断是否所有人都会签完毕，如果有主办人会签的话，不包含主办人
                            unset($map);
                            $map['run_id'] = I('run_id');
                            $map['flow_prcs'] = $data['prcs_id'];
                            $map['op_flag'] = 0;    //查询所有从办人
                            $finish = M('flow_run_prcs')->field('run_id,flow_prcs,op_flag,deliver_time,prcs_flag')->where($map)->select();
                            $count = 0;
                            foreach ($finish as $f_key => $f_row) {
                                //标记为4
                                if ($f_row['prcs_flag'] != 4) {
                                    $count ++;
                                }
                            }
                            if ($default != 2) {
                                //有主办人会签，由主办人转交下一步
                                if ($row['op_flag'] && $count == 0) {
                                    $count = 0;
                                } else {
                                    $count = 1;
                                }
                            }
                            $return['info'] = '办理结束';
                            if (!$count) {
                                $return['url'] = U('nextStep', array('run_id' => I('run_id'), 'flow_id' => $data['flow_id'], 'prcs_id' => $data['prcs_id']));
                            } else {
                                $return['url'] = U('Flow/lists', array("type" => 2));  //办理完毕返回已办结列表
                            }
                        } else {
                            $return['url'] = U('nextStep', array('run_id' => I('run_id'), 'flow_id' => $data['flow_id'], 'prcs_id' => $data['prcs_id']));
                        }
                    } else {
                        $return['info'] = '修改失败';
                    }
                } else {
                    $return['info'] = '请填写会签意见';
                }
            } else {
                //插入一条数据到flow_run表里
                $form_name = M('flow_form_type')->where('form_id=' . $data['form_id'])->getField('form_name'); //获取表单名
                $data['run_name'] = $form_name . '(' . date('Y-m-d H:i:s') . ')';
                $data['flow_id'] = M('flow_type')->where('form_id=' . $data['form_id'])->getField('flow_id');
                $data['begin_user'] = session('user_id');
                $data['begin_dept'] = session('dept_id');
                $data['begin_time'] = date('Y-m-d H:i:s');
                $data['del_flag'] = 0;
                $run_id = M('flow_run')->order('run_id DESC')->limit(1)->getField('run_id');
                $data['run_id'] = $run_id + 1;
                $txt = 'run_name=' . $data['run_name'] . ' flow_id=' . $data['flow_id'] . ' begin_user=' . $data['begin_user'] . ' begin_dept' . $data['begin_dept'] . ' begin_time' . $data['begin_time'] . ' del_flag' . $data['del_flag'] . ' run_id' . $data['run_id'];
//                echo $txt;die;
                $res = M('flow_run')->add($data);

                if ($res !== false) {
                    //添加flow_run_prcs表
                    $pData['run_id'] = $data['run_id'];
                    $pData['prcs_id'] = 1;
                    $pData['user_id'] = session('user_id');
                    $pData['prcs_dept'] = session('dept_id');
                    $pData['parent_prcs_id'] = 0;   //上一步流程prcs_id
                    $pData['prcs_time'] = date('Y-m-d H:i:s');
                    $pData['prcs_flag'] = 2;    //办理中,如果转交下一步，此字段改为3，已转交
                    $pData['flow_prcs'] = 1;
                    if ($pData['flow_prcs'] > 1) {
                        $pData['parent'] = $pData['flow_prcs'] - 1;
                    }
                    $pData['create_time'] = date('Y-m-d H:i:s');
                    M('flow_run_prcs')->add($pData);

                    //添加flow_run_log表
                    $log_id = M('flow_run_log')->order('log_id DESC')->limit(1)->getField('log_id');
                    $lData['log_id'] = $log_id + 1;
                    $lData['run_id'] = $data['run_id'];
                    $lData['run_name'] = $data['run_name'];
                    $lData['flow_id'] = $data['flow_id'];
                    $lData['prcs_id'] = 1;
                    $lData['flow_prcs'] = 1;
                    if ($lData['flow_prcs'] > 1) {
                        $lData['parent'] = $lData['flow_prcs'] - 1;
                    }
                    $lData['user_id'] = session('user_id');
                    $lData['time'] = date('Y-m-d H:i:s');
                    $lData['ip'] = gethostbyname($_ENV['COMPUTERNAME']);
                    $lData['type'] = 1;
                    M('flow_run_log')->add($lData);

                    $new_run_id = $run_id + 1;
                    $runRow = M('flow_run')->where('run_id=' . $new_run_id)->find();

                    //添加flow_data_表
                    foreach ($data as $key => $row) {
                        $newData[strtolower($key)] = $row;
                    }
                    $newData['run_id'] = $new_run_id;
                    $newData['run_name'] = $runRow['run_name'];
                    $newData['begin_time'] = date('Y-m-d H:i:s');
                    $table = 'flow_data_' . $runRow['flow_id'];
                    //如何user_ids存在的话，插入多条数据
                    if (I('user_ids')) {
                        $newData['users'] = implode(',', I('user_ids'));
                        $newData['begin_user'] = session('user_id');
                        $dataRes = M($table)->add($newData);
                    } else {
                        $newData['begin_user'] = session('user_id');
                        $dataRes = M($table)->add($newData);
                    }

                    if ($dataRes) {
                        if ($type) {
                            $return['info'] = '保存成功';
                        } else {
                            $return['url'] = U('nextStep', array('run_id' => $new_run_id, 'flow_id' => $data['flow_id'], 'form_id' => $data['form_id']));
                        }
                    } else {
                        $return['info'] = 'flow_run_data save fail';
                    }
                } else {
                    $return['info'] = 'save all fail';
                }
            }
            $this->ajaxReturn($return);
        }

        //获取表单
        $map['form_id'] = I('id');
        $form = M('flow_form_type')->where($map)->find();
        $this->form = $form;

        //获取flow_id
        if (I('run_id')) {
            $flow_id = M('flow_run')->where('run_id=' . I('run_id'))->getField('flow_id');
            $this->flow_id = I('flow_id');
        }

        //新建表单时，判断是否允许上传附件  by zyh 2018/7/24
        $flow = M('flow_type')->field('flow_id,flow_name,form_id,flow_doc,flow_sort,view_priv')->where('flow_id=' . I('flow_id'))->find();
        $this->flowDoc = $flow['flow_doc'] ? 1 : 0;   //是否允许上传附件

        if (!I('run_id')) {
            $prcs_id = 1;
            $op = 1;
        } else {
            $prcs_id = I('prcs_id') ? I('prcs_id') : I('currPrcs');

            //判断当前用户是否主办，主办=>转交下一步；经办=>办理完毕
            unset($map);
            $map['run_id'] = I('run_id');
            if ($prcs_id) {
                $map['flow_prcs'] = $prcs_id;
            }
            $map['user_id'] = session('user_id');
            $op = M('flow_run_prcs')->where($map)->getField('op_flag');
            //判断当前步骤是否为会签 
            $pMap['flow_id'] = $flow_id;
            $pMap['prcs_id'] = $prcs_id;
            $prcsName = M('flow_process')->where($pMap)->getField('prcs_name');
            if ($op == 1 && strpos($prcsName, '会签') !== false) {
                $op = 0;
            } elseif ($op == 0 && strpos($prcsName, '会签') !== false) {
                $op = 0;
            } else if (I('currPrcs') == 1) {
                $op = 1;
            }

            //修改prcs_flag状态,当前用户为2，添加开始时间
            unset($map);
            $map['run_id'] = I('run_id');
            $map['user_id'] = session('user_id');
            $map['prcs_id'] = I('currPrcs');
            $flag = M('flow_run_prcs')->where($map)->getField('prcs_flag');
            if ($flag == 1) {
                $data['prcs_flag'] = 2;
                $data['prcs_time'] = date('Y-m-d H:i:s');
                $data['mobile_flag'] = 1;
                M('flow_run_prcs')->where($map)->save($data);   //当前用户状态改为2
            }
            unset($map['user_id']);
            unset($map['prcs_id']);
            $map['prcs_id'] = I('currPrcs') - 1;
            M('flow_run_prcs')->where($map)->save(array('prcs_flag' => 4));   //上一步骤用户状态改为4

            $info = M('flow_run')->where('run_id=' . I('run_id'))->find();
            //获取附件
            $uploads = downloadFile($info['attachment_id'], $info['attachment_name'], 'workflow', $info['uploads'], $info['uploads_url']);
            $this->uploads = $uploads;

            /*
             * 2018/3/22  增加第一步表单未转交后的修改功能
             * form.js 自动加载方法通过flow_id是否存在判断是否可修改
             */
            if (I('currPrcs') == 1) {
                $info['flow_id'] = 0;
                $info['isEdit'] = 'edit';
            }
            $this->info = $info;
//             print_r($info);

            if ($this->flowDoc == 1) {
                $process = M('flow_process')->where(array('flow_id' => I('flow_id'), 'prcs_id' => I('currPrcs')))->find();
                $this->editDoc = $process['attach_edit_priv'];   //判断当前步骤是否允许编辑附件
                $this->feedback = $process['feedback'];     //当前步骤是否允许会签
            }
        }
//        echo $op;
        $this->prcs = $prcs_id ? $prcs_id : I('currPrcs');
        $this->currPrcs = I('currPrcs') ? I('currPrcs') : 1;    //当前流程步骤标识
        //   $this->prcs = 1;  //测试会签意见区
        $this->op = $op;
        //获取当前部门
        $this->department = getDeptName(session('dept_id'));
        $this->form_id = I('id');
        $this->run_id = I('run_id');
        $this->flow_id = I('flow_id');
        $this->flowType = I('flowtype') ? I('flowtype') : '';

        //获取当前步骤名称
        $this->stepName = getFlowProcessName(I('flow_id'), $this->currPrcs);

        //当前步骤标记号
        if (I('run_id')) {
            $this->prcsNum = M('flow_run_prcs')->where('user_id="' . session('user_id') . '" and run_id = ' . I('run_id'))->order('prcs_id desc')->limit(1)->getField('prcs_id');  //当前实际步骤数
        }

        $this->display();
    }

    //显示已办流程页面
    public function showForm() {
        //获取表单
        $map['form_id'] = I('id');
        $form = M('flow_form_type')->where($map)->find();
        $this->form = $form;

        $prcs_id = I('prcs_id');

        //获取手机端上传的附件
        $info = M('flow_run')->where('run_id=' . I('run_id'))->find();
        //获取PC端文件
        $uploads = downloadFile($info['attachment_id'], $info['attachment_name'], 'workflow', $info['uploads'], $info['uploads_url']);

        $this->uploads = $uploads;
        $this->info = $info;

        //获取会签内容
        unset($map);
        $map['run_id'] = I('run_id');
        $feeds = M('flow_run_feedback')->where($map)->order('prcs_id')->select();
        foreach ($feeds as $key => $row) {
            $pMap['flow_id'] = $info['flow_id'];
            $pMap['prcs_id'] = $row['prcs_id'];
            $feeds[$key]['prcs_name'] = M('flow_process')->where($pMap)->getField('prcs_name');
        }
        $this->feeds = $feeds;

        //获取流程图
        $runPrcs = M('flow_run_prcs')->field('run_id,user_id,prcs_time,deliver_time,prcs_flag,flow_prcs')->where($map)->order('prcs_id')->select();
        $sql = 'select d.prcs_name,d.prcs_id,c.prcs_id as id,c.prcs_flag from flow_process d , (select a.flow_id,b.prcs_id,b.flow_prcs,b.prcs_flag from flow_run a,flow_run_prcs b where a.run_id = b.run_id and a.run_id = ' . I('run_id') . ' order by b.prcs_id asc) as c where d.flow_id = c.flow_id and d.prcs_id = c.flow_prcs';
        $arr = M()->query($sql);
        foreach ($arr as $key => $row) {
            $process[$row['id']] = $row;
        }
        foreach ($process as $k1 => $r1) {
            foreach ($runPrcs as $k2 => $r2) {
                if ($r2['prcs_time'] && $r2['deliver_time']) {
                    $r2['dec'] = timediff(strtotime($r2['deliver_time']), strtotime($r2['prcs_time']));
                }
                if (($r1['prcs_id'] == $r2['flow_prcs']) && ($r1['prcs_flag'] == $r2['prcs_flag'])) {
                    $process[$k1]['data'][] = $r2;
                }
                //有些流程k1!=r2[flow_prcs]，会导致有的步骤不显示 18/5/7改回原来的
//                if ($k1 == $r2['flow_prcs']) {
//                    $process[$k1]['data'][] = $r2;
//                }
            }
        }
//          print_r($process);
        $process = $this->mySort($process, 'id');
        $this->process = $process;

        //获取flow_id
        $this->flow_id = M('flow_run')->where('run_id=' . I('run_id'))->getField('flow_id');
        $this->form_id = I('id');
        $this->run_id = I('run_id');
        $this->prcs = $prcs_id;
        $this->display();
    }

    //二维数组排序
    private function mySort($arrays, $sort_key, $sort_order = SORT_ASC, $sort_type = SORT_NUMERIC) {
        if (is_array($arrays)) {
            foreach ($arrays as $array) {
                if (is_array($array)) {
                    $key_arrays[] = $array[$sort_key];
                } else {
                    return false;
                }
            }
        } else {
            return false;
        }
        array_multisort($key_arrays, $sort_order, $sort_type, $arrays);
        return $arrays;
    }

    //获取表单中需要自动赋值的字段 add zyh 2018/7/24
    public function getFormAutoValue() {
        $map['flow_id'] = I('flow_id');
        $map['prcs_id'] = 1;
        $item = M('flow_process')->where($map)->getField('prcs_item_auto');
        $item = $item ? explode(',', rtrim($item, ',')) : '';
        foreach ($item as $key => $row) {
            if (strpos($row, '人') !== false || (strpos($row, '姓名') !== false)) {
                $data[$key]['field'] = $row;
                $data[$key]['value'] = getChineseName(session('user_id'));
            }
            if (strpos($row, '时间') !== false || (strpos($row, '日期') !== false)) {
                $data[$key]['field'] = $row;
                $data[$key]['value'] = date('Y-m-d H:i:s');
            }
            if (strpos($row, '部门') !== false || $row == '部门') {
                $data[$key]['field'] = $row;
                $data[$key]['value'] = getDeptName(session('dept_id'));
            }
        }
        $this->ajaxReturn($data);
    }

    //获取表单中不为空的字段
    public function getFormNotNullField() {
        //增加转出条件提示 add zyh 2018/7/24
        $map['flow_id'] = I('flow_id');
        $map['prcs_id'] = 1;
        $process = M('flow_process')->where($map)->find();
        $prcsOut = $process['prcs_out'];
        if ($prcsOut != '') {
            $prcsOut = str_replace("\n", "<br>", $prcsOut);
            $prcsOut = explode('<br>', $prcsOut);
        }

        $this->ajaxReturn($prcsOut);
    }

    //导出流程
    public function download() {
        //获取表单
        $map['form_id'] = I('id');
        $form = M('flow_form_type')->where($map)->find();
        $this->form = $form;

        $prcs_id = I('prcs_id');

        //获取手机端上传的附件
        $info = M('flow_run')->where('run_id=' . I('run_id'))->find();
        //获取PC端文件
        $uploads = downloadFile($info['attachment_id'], $info['attachment_name'], 'workflow', $info['uploads'], $info['uploads_url']);

        $this->uploads = $uploads;
        $this->info = $info;

        //获取会签内容
        unset($map);
        $map['run_id'] = I('run_id');
        $feeds = M('flow_run_feedback')->where($map)->order('prcs_id')->select();
        foreach ($feeds as $key => $row) {
            $pMap['flow_id'] = $info['flow_id'];
            $pMap['prcs_id'] = $row['prcs_id'];
            $feeds[$key]['prcs_name'] = M('flow_process')->where($pMap)->getField('prcs_name');
        }
        $this->feeds = $feeds;

        //获取流程图
        $runPrcs = M('flow_run_prcs')->field('run_id,user_id,prcs_time,deliver_time,prcs_flag,flow_prcs')->where($map)->order('prcs_id')->select();
        $sql = 'select d.prcs_name,d.prcs_id,c.prcs_id as id,c.prcs_flag from flow_process d , (select a.flow_id,b.prcs_id,b.flow_prcs,b.prcs_flag from flow_run a,flow_run_prcs b where a.run_id = b.run_id and a.run_id = ' . I('run_id') . ' order by b.prcs_id asc) as c where d.flow_id = c.flow_id and d.prcs_id = c.flow_prcs';
        $arr = M()->query($sql);
        foreach ($arr as $key => $row) {
            $process[$row['id']] = $row;
        }
        foreach ($process as $k1 => $r1) {
            foreach ($runPrcs as $k2 => $r2) {
                if ($r2['prcs_time'] && $r2['deliver_time']) {
                    $r2['dec'] = timediff(strtotime($r2['deliver_time']), strtotime($r2['prcs_time']));
                }
                if (($r1['prcs_id'] == $r2['flow_prcs']) && ($r1['prcs_flag'] == $r2['prcs_flag'])) {
                    $process[$k1]['data'][] = $r2;
                }
            }
        }
//          print_r($process);
        $this->process = $process;

        //获取flow_id
        $this->flow_id = M('flow_run')->where('run_id=' . I('run_id'))->getField('flow_id');
        $this->form_id = I('id');
        $this->run_id = I('run_id');
        $this->prcs = $prcs_id;
        $this->download = I('download') . '.html';
        $this->display();
    }

    //转交下一步骤
    public function nextStep() {
        if (IS_AJAX && isset($_POST)) {
            $data = I('post.');

            //当前用户流程信息
            $one = M('flow_run_prcs')->where('run_id=' . $data['run_id'])->order('prcs_id DESC')->limit(1)->find();

            //发送提示消息
//            vendor('Mpwexin');
//            $mp_weixin = new \Mpwexin();
//            $web = M('web')->where('id=' . session('webid'))->find();
            $flow_name = M('flow_run')->where(array('run_id' => $data['run_id'], 'flow_id' => $data['flow_id']))->getField('run_name');
            $form = M('flow_type')->field('flow_name,form_id')->where(array('flow_id' => $data['flow_id']))->find();
            //获取流程发起人
            $uMap['run_id'] = $data['run_id'];
            $uMap['flow_prcs'] = 1;
            $creator = M('flow_run_prcs')->where($uMap)->getField('user_id');
            $currPrcs = $one['prcs_id'] + 1;
            $content = "您有一条新流程请尽快办理，\n流程名：<a href=\"http://www.jsumt.com:88/index.php/Index/Index/form/id/" . $form['form_id'] . "/run_id/" . $data['run_id'] . "/prcs_id/" . $currPrcs . "/webid/" . $this->webid . "\">" . $flow_name . "，发起人：" . getChineseName($creator) . "</a>，转交人：" . getChineseName(session('user_id'));
            $sendContent = "您发起的”<a href='http://www.jsumt.com:88/index.php/Index/Index/form/id/" . $form['form_id'] . "/run_id/" . $data['run_id'] . "/prcs_id/" . $currPrcs . "/webid/" . $this->webid . "'>" . $flow_name . "</a>“的流程" . getChineseName(session('user_id')) . "已审批！";


            //往flow_run_prcs里添加数据，每个经办人一条
            $pData['run_id'] = $data['run_id'];
            $pData['prcs_id'] = $one['prcs_id'] + 1;
            $pData['prcs_flag'] = 1;    //未接收
            $pData['flow_prcs'] = $data['prcs_id'];
            $pData['parent'] = $one['flow_prcs'];
            $pData['create_time'] = date('Y-m-d H:i:s');
            $pData['parent_prcs_id'] = $one['prcs_id'];

            //去重条件
            $dMap['run_id'] = $data['run_id'];
            $dMap['prcs_id'] = $one['prcs_id'] + 1;

            //只有主办人
            if ($data['user_id'] && !$data['user_ids']) {
                //去重
                $dMap['user_id'] = $data['user_id'];
                $has = M('flow_run_prcs')->where($dMap)->count();
                if (!$has) {
                    $pData['user_id'] = $data['user_id'];
                    $pData['prcs_dept'] = M('user')->where('user_id="' . $data['user_id'] . '"')->getField('dept_id');
                    $pData['op_flag'] = 1;
                    $resMain = M('flow_run_prcs')->add($pData);

//                    setWeixinMsg($data['user_id'], $content, $this->webid); //发给下一步经办人
                }
            } else if ($data['user_ids'] && !$data['user_id']) {
                //只有经办人
                foreach ($data['user_ids'] as $key => $row) {
                    //去重
                    $dMap['user_id'] = $row;
                    $has = M('flow_run_prcs')->where($dMap)->count();
                    if (!$has) {
                        $pData['user_id'] = $row;
                        $pData['prcs_dept'] = M('user')->where('user_id="' . $row . '"')->getField('dept_id');
                        $pData['op_flag'] = 0;
                        $resOther = M('flow_run_prcs')->add($pData);

//                        setWeixinMsg($row, $content, $this->webid);
                    }
                }
            } else if ($data['user_id'] && $data['user_ids']) {
                //两种人都有
                array_push($data['user_ids'], $data['user_id']);
                $data['user_id'] = array_unique($data['user_ids']);
                foreach ($data['user_id'] as $key => $row) {
                    //去重
                    $dMap['user_id'] = $row;
                    $has = M('flow_run_prcs')->where($dMap)->count();
                    if (!$has) {
                        $pData['user_id'] = $row;
                        $pData['prcs_dept'] = M('user')->where('user_id="' . $row . '"')->getField('dept_id');
                        if ($key == 0) {
                            $pData['op_flag'] = 1;
                        } else {
                            $pData['op_flag'] = 0;
                        }
                        $resAll = M('flow_run_prcs')->add($pData);
                    }
                }
//                setWeixinMsg($data['user_id'], $content, $this->webid);
            }

            if ($resMain || $resOther || $resAll) {
                //是否为会签
                $fMap['flow_id'] = $data['flow_id'];
                $fMap['prcs_id'] = $data['over_prcs_id'];
                $prcsName = M('flow_process')->where($fMap)->getField('prcs_name');

                $rMap['run_id'] = $data['run_id'];
                $rMap['flow_prcs'] = $data['over_prcs_id'];
                if (strpos($prcsName, '会签') !== false) {
                    $rMap['user_id'] = $data['over_user'];
                }
                $rData['deliver_time'] = date('Y-m-d H:i:s');
                $rData['prcs_flag'] = 3;
                M('flow_run_prcs')->where($rMap)->save($rData);
            }

            if ($res !== false) {
                //修改log表（上一步骤）
                unset($map);
                $map['run_id'] = $data['run_id'];
                $map['flow_id'] = $data['flow_id'];
                $map['prcs_id'] = $one['prcs_id'];
                $map['flow_prcs'] = $one['flow_prcs'];
                $names = implode(',', $data['user_names']);
                $sData['content'] = '转交步骤' . $pData['flow_prcs'] . '，办理人：' . $names;
                M('flow_run_log')->where($map)->save($sData);

                //添加log表（转交后的步骤）
                $lData['run_id'] = $data['run_id'];
                $lData['run_name'] = M('flow_run')->where(array('run_id' => $data['run_id'], 'flow_id' => $data['flow_id']))->getField('run_name');
                $lData['flow_id'] = $data['flow_id'];
                $lData['prcs_id'] = $pData['prcs_id'];
                $lData['flow_prcs'] = $pData['flow_prcs'];
                //获取转交后步骤的用户名
                $uMap['run_id'] = $data['run_id'];
                $uMap['flow_prcs'] = $data['prcs_id'];
                $uMap['prcs_flag'] = 1;
                $lData['user_id'] = session('user_id');
                $lData['time'] = date('Y-m-d H:i:s');
                $lData['ip'] = gethostbyname($_ENV['COMPUTERNAME']);
                $lData['type'] = 1;
                $res = M('flow_run_log')->add($lData);
            }

            /*
             * 关联和考勤相关的流程
             */
            //取相关的flow_id
            unset($where);
            $where['_string'] = ' flow_name like "请假申请%" or flow_name like "出差申请%" or flow_name like "外出申请%" or flow_name like "加班申请%"';
            $flow_ids = M('flow_type')->where($where)->getField('flow_id', true);

            if (in_array($data['flow_id'], $flow_ids) && ($one['flow_prcs'] == 2)) {
                //取表单项数据
                $flow_data = M('flow_data_' . $data['flow_id'])->where('run_id=' . $data['run_id'])->find();

                switch ($data['flow_id']) {
                    case 146:   //请假
                        $checkRow = M('attend_leave')->where('run_id=' . $flow_data['run_id'])->count();
                        if (!$checkRow) {
                            $attData['user_id'] = $flow_data['begin_user'];
                            $attData['leave_type2'] = $flow_data['data_35'];
                            $attData['leave_date1'] = $flow_data['data_56'];
                            $attData['leave_date2'] = $flow_data['data_57'];
                            $attData['leave_type'] = $flow_data['data_63'];
                            $attData['allow'] = 0;
                            $attData['leave_duration'] = $flow_data['data_66'];
                            $attData['run_id'] = $flow_data['run_id'];
                            $res = M('attend_leave')->add($attData);

                            //扣除对应年假
                            if ($res) {
                                switch ($flow_data['data_35']) {
                                    case '年假':
                                        $ableYear = M('userinfo')->where('user_id="' . $flow_data['begin_user'] . '"')->getField('able_year');
                                        $infoData['able_year'] = $ableYear - floatval($flow_data['data_66']);
                                        break;
                                    case '调休':
                                        $ableVacation = M('userinfo')->where('user_id="' . $flow_data['begin_user'] . '"')->getField('able_vacation');
                                        $infoData['able_vacation'] = $ableVacation - floatval($flow_data['data_66']);
                                        break;
                                }
                                $infoMap['user_id'] = $flow_data['begin_user'];
                                M('userinfo')->where($infoMap)->save($infoData);
                            }
                        }
                        break;
                    case 163:   //外出
                        $checkRow = M('attend_out')->where('run_id=' . $flow_data['run_id'])->count();
                        if (!$checkRow) {
                            $attData['user_id'] = $flow_data['begin_user'];
                            $attData['create_date'] = $flow_data['begin_time'];
                            $attData['submit_time'] = substr($flow_data['data_56'], 0, 10);
                            $attData['out_time1'] = substr($flow_data['data_56'], 11, 5);
                            $attData['out_time2'] = substr($flow_data['data_57'], 11, 5);
                            $attData['allow'] = 0;
                            $attData['status'] = 0;
                            $attData['out_type'] = $flow_data['data_53'];
                            $attData['run_id'] = $flow_data['run_id'];
                            $attData['time_long'] = $flow_data['data_52'];
                            M('attend_out')->add($attData);
                        }
                        break;
                    case 150:   //出差
                        $checkRow = M('attend_evection')->where('run_id=' . $flow_data['run_id'])->count();
                        if (!$checkRow) {
                            $attData['evection_dest'] = $flow_data['data_4'];
                            $attData['evection_date1'] = $flow_data['data_5'];
                            $attData['evection_date2'] = $flow_data['data_6'];
                            $attData['allow'] = 1;
                            $attData['status'] = 1;
                            $attData['reason'] = $flow_data['data_9'];
                            $attData['run_id'] = $flow_data['run_id'];
                            if ($flow_data['users']) {
                                $users = explode(',', $flow_data['users']);
                                foreach ($users as $u_key => $u_row) {
                                    $attData['user_id'] = $u_row;
                                    M('attend_evection')->add($attData);
                                }
                            }
//                            print_r($attData);die;
                            $attData['user_id'] = $flow_data['begin_user'];
                            M('attend_evection')->add($attData);
                        }
                        break;
                    case 145:   //加班
                        $checkRow = M('attendance_overtime')->where('run_id=' . $flow_data['run_id'])->count();
                        if (!$checkRow) {
                            $attData['user_id'] = $flow_data['begin_user'];
                            $attData['record_time'] = $flow_data['begin_time'];
                            $attData['start_time'] = $flow_data['data_57'];
                            $attData['end_time'] = $flow_data['data_58'];
                            $attData['overtime_hours'] = $flow_data['data_60'];
                            $attData['overtime_content'] = $flow_data['data_51'];
                            $attData['allow'] = 1;
                            $attData['status'] = 0;
                            $attData['run_id'] = $flow_data['run_id'];
                            $res = M('attendance_overtime')->add($attData);
                        }
                        //增加调休
                        if ($res) {
                            $ableVacation = M('userinfo')->where('user_id="' . $flow_data['begin_user'] . '"')->getField('able_vacation');
                            $overtime = floatval($flow_data['data_60']) / 8;
                            $infoData['able_vacation'] = $ableVacation + substr(sprintf("%.4f", $overtime), 0, -1);
                            $infoMap['user_id'] = $flow_data['begin_user'];
                            M('userinfo')->where($infoMap)->save($infoData);
                        }
                        break;
                }
            }

            if ($res !== false) {
                //发提醒给流程发起人
                if ($data['prcs_id'] > 1) {
//                setWeixinMsg($creator, $sendContent, $this->webid);
                }

                $return['info'] = '转交成功';
                $return['url'] = U('lists', array('type' => 2)); //返回已办结列表
            } else {
                $return['info'] = '转交失败';
            }

            $this->ajaxReturn($return);
        }

        $run_id = I('run_id');
        $flow_id = I('flow_id');
        $prcs_id = I('prcs_id') ? I('prcs_id') : 1;
        //获取流程信息
        $runs = M('flow_run')->where(array('run_id' => $run_id))->find();
        //添加流程名及表单id
        $flowType = M('flow_type')->field('flow_name,form_id')->where(array('flow_id' => $flow_id))->find();
        $runs['flow_name'] = $flowType['flow_name'];
        $runs['form_id'] = $flowType['form_id'];
        //获取该流程步骤
        $steps = M('flow_process')->field('prcs_id,prcs_name,prcs_dept,prcs_priv,prcs_user,prcs_to,feedback,prcs_in,prcs_in_set,allow_back')->where(array('flow_id' => $flow_id))->order('prcs_id')->select();
        foreach ($steps as $key => $row) {
            if ($row['prcs_id'] == $prcs_id) {
                $map['run_id'] = $run_id;
                $map['flow_prcs'] = $row['prcs_id'];
                $users = M('flow_run_prcs')->field('user_id,flow_prcs,prcs_flag')->where($map)->select();
                $steps[$key]['user'] = $users;
            }
        }
        $runs['step'] = $steps;
        $this->runs = $runs;


        //print_r($form_data);die;
        //获取下一步骤
        unset($map);
        $map['flow_id'] = $flow_id;
        $map['prcs_id'] = $prcs_id;
        $prcs_to = M('flow_process')->field('prcs_id,prcs_name')->where($map)->getField('prcs_to');
        if (!$prcs_to) {
            $map['prcs_id'] = $prcs_id + 1;
        } else {
            $prcs_to = rtrim($prcs_to, ',');
            $prcs_to = explode(',', $prcs_to);
            $map['prcs_id'] = array('in', $prcs_to);
        }

        $flag = 0;
        $nexts = M('flow_process')->field('prcs_id,prcs_name,prcs_dept,prcs_priv,prcs_user,prcs_to,auto_type,auto_user,user_filter,top_default,feedback,prcs_in,prcs_in_set,allow_back,auto_type,condition_desc')->where($map)->select();
        $sort = array(
            'direction' => 'SORT_ASC', //排序顺序标志 SORT_DESC 降序；SORT_ASC 升序  
            'field' => 'prcs_id', //排序字段  
        );
        $arrSort = array();
        foreach ($nexts AS $uniqid => $row) {
            foreach ($row AS $key => $value) {
                $arrSort[$key][$uniqid] = $value;
            }
        }
        array_multisort($arrSort[$sort['field']], constant($sort['direction']), $nexts);
        $count = count($nexts);
        $num = 0;
        if ($nexts[0]) {
            $table = 'flow_data_' . $flow_id;

            //获取form表单中的key
            $html = M('flow_form_type')->where('form_id=' . $runs['form_id'])->getField('print_model');
            preg_match_all('/[^s]name[\s]*?=[\s]*?([\'\"])(.*?)\1/', $html, $match);
            $htmlName = $match[2];
            preg_match_all('/title[\s]*?=[\s]*?([\'\"])(.*?)\1/', $html, $match);
            $htmlTitle = $match[2];
            for ($i = 0; $i < count($htmlTitle); $i++) {
                if (strpos($htmlName[$i], 'OTHER') === false) {
                    $htmlArr[strtolower($htmlName[$i])] = $htmlTitle[$i];
                }
            }

            foreach ($nexts as $key => $row) {
                $tmp_data = M($table)->where('run_id=' . $run_id)->find();
                foreach ($tmp_data as $t_k => $t_v) {
                    if (strpos($t_k, 'data_') !== false) {
                        $form_data[$t_k] = $t_v;
                    }
                }
//                print_r($form_data);
                if ($row['prcs_in']) {
                    $prcs_in_desc = str_replace("\n", "<br>", $row['prcs_in']);
                    $prcs_in_desc = str_replace("'", " ", $prcs_in_desc);
//                    echo $prcs_in_DESC;
                    $sql = getFormCondition($prcs_in_desc, $form_data, $prcs_id, $row['prcs_in_set'], $htmlArr);
//                    echo $sql;
                    preg_match_all('/\[.*like|not like\%/U', $sql, $arr);
                    $new = [];
                    foreach ($arr[0] as $ak => $av) {
                        $last = strripos($av, '[');
                        $new[] = substr($av, $last);
                    }
                    preg_match_all('/(?:%)(.*)(?:%)/U', $sql, $arr1);
                    $params = $arr1[1];
                    $tmp1 = array();
                    foreach ($new as $k => $v) {
                        $v = explode(']', $v);
                        $v_k = trim($v[0], '[');
                        $v_v = trim($v[1]);
                        $v[0] = $v[0] . ']';
                        if ($v[0] == '[CUR_USER_DEPT]' || ($v[0] == '[CUR_USER_PRIV]') || ($v[0] == '[CUR_USER_PRIV_OTHER]') || ($v[0] == '[FLOW_USER_PRIV]')) {
                            //$tmp1[$v_v] = $v_k;
                            $tmp1[][$v_v] = $v_k;
                        }
                    }

                    $params = getDartPrivId($tmp1, $params);
                    $nexts[$key]['sql'] = $sql;
                    if (strpos($sql, '[CUR_USER_DEPT]') !== false) {    //当前主办人部门
                        foreach ($tmp1 as $t_key => $t_val) {
                            $tempvalue = array_values($t_val);
                            $tempkey = key($t_val);

                            if ($tempvalue[0] == 'CUR_USER_DEPT') {
                                //$sql = str_replace('[当前主办人部门]', 'c.dept_id', $sql);
                                $sql = preg_replace("/%.+部%/is", '%' . trim($params[$t_key]) . '%', $sql);
                                $sql_0 = str_replace('[CUR_USER_DEPT]', 'c.dept_id', $sql);
                                $sql_1 = str_replace('[CUR_USER_DEPT]', 'c.dept_id_other', $sql);
                                $sql_2 = strstr($sql_1, 'c');
                                if ($tempkey == 'not like')
                                    $sql = $sql_0 . " and " . $sql_2;
                                elseif ($tempkey == 'like')
                                    $sql = $sql_0 . " or " . $sql_2;
                            }
                        }
                    }

                    if (strpos($sql, '[CUR_FLOW_PRCS]') !== false) {    //当前流程设计步骤号
                        $sql = str_replace('[CUR_FLOW_PRCS]', 'b.flow_prcs', $sql);
                    }

                    if (strpos($sql, '[CUR_USER_PRIV_OTHER]') !== false) {      //当前主办人辅助角色
                        foreach ($tmp1 as $t_key2 => $t_val2) {
                            $tempvalue = array_values($t_val2);
                            $tempkey = key($t_val2);

//                            if ($tempvalue[0] == 'CUR_USER_PRIV_OTHER') {
//                                $sql = str_replace('[CUR_USER_PRIV_OTHER]', 'c.user_priv_other', $sql);
//                                $sql = preg_replace('/[\x7f-\xff]+/', ltrim($params[$t_key2]), $sql);
//                            }
                            //update by zyh 2018-7-20 remark: 多个角色ID时需分开组sql
                            $nsql = '';
                            if ($tempvalue[0] == 'CUR_USER_PRIV_OTHER') {
                                $paramsArr = explode(',', rtrim($params[$t_key1]));
                                $nsql .= '(';
                                foreach ($paramsArr as $p_key => $p_val) {
                                    if ($tempkey == 'not like') {
                                        $nsql .= 'c.user_priv_other not like "%' . $p_val . '%" and ';
                                    } else {
                                        $nsql .= 'c.user_priv_other like "%' . $p_val . '%" or ';
                                    }
                                }
                                $nsql = rtrim($nsql, ' and ');
                                $nsql = rtrim($nsql, ' or ');
                                $sql = preg_replace('/\[CUR_USER_PRIV_OTHER.*%\'"/', $nsql, $sql) . ')';
                            }
                        }
                    }
                    if (strpos($sql, '[CUR_USER_PRIV]') !== false) {    //当前主办人角色
                        foreach ($tmp1 as $t_key1 => $t_val1) {
                            $tempvalue = array_values($t_val1);
                            $tempkey = key($t_val1);

//                            if ($tempvalue[0] == 'CUR_USER_PRIV') {
//                                $sql = str_replace('[CUR_USER_PRIV]', 'c.user_priv', $sql);
//                                $sql = preg_replace('/[\x7f-\xff]+/', trim($params[$t_key1]), $sql);
//                            }
                            //update by zyh 2018-7-20 remark: 多个角色ID时需分开组sql
                            $nsql = '';
                            if ($tempvalue[0] == 'CUR_USER_PRIV') {
                                $paramsArr = explode(',', rtrim($params[$t_key1]));
                                $nsql .= '(';
                                foreach ($paramsArr as $p_key => $p_val) {
                                    if ($tempkey == 'not like') {
                                        $nsql .= 'c.user_priv not like "%' . $p_val . '%" and ';
                                    } else {
                                        $nsql .= 'c.user_priv like "%' . $p_val . '%" or ';
                                    }
                                }
                                $nsql = rtrim($nsql, ' and ');
                                $nsql = rtrim($nsql, ' or ');
                                $sql = preg_replace('/\[CUR_USER_PRIV.*%\'"/', $nsql, $sql) . ')';
                            }
                        }
                    }
                    if (strpos($sql, '[FLOW_USER_PRIV]') !== false) {      //流程发起人角色
                        foreach ($tmp1 as $t_key1 => $t_val1) {
                            $tempvalue = array_values($t_val1);
                            $tempkey = key($t_val1);

//                            if ($tempvalue[0] == 'FLOW_USER_PRIV') {
//                                $sql = str_replace('[FLOW_USER_PRIV]', 'c.user_priv', $sql);
//                                $sql = preg_replace('/[\x7f-\xff]+/', trim($params[$t_key1]), $sql);
//                            }
                            $nsql = '';
                            if ($tempvalue[0] == 'FLOW_USER_PRIV') {
                                $paramsArr = explode(',', rtrim($params[$t_key1]));
                                $nsql .= '(';
                                foreach ($paramsArr as $p_key => $p_val) {
                                    if ($tempkey == 'not like') {
                                        $nsql .= 'c.user_priv not like "%' . $p_val . '%" and c.user_priv_other not like "%' . $p_val . '%" and ';
                                    } else {
                                        $nsql .= 'c.user_priv like "%' . $p_val . '%" or c.user_priv_other like "%' . $p_val . '%" or ';
                                    }
                                }
                                $nsql = rtrim($nsql, ' and ');
                                $nsql = rtrim($nsql, ' or ');
                                $nsql .= ')';
                                $sql = '(' . preg_replace('/\[FLOW_USER_PRIV.*%\'"/', $nsql, $sql) . ')';
                            }
                        }
                    }

                    //判断条件是否成立，自动选择对应流程
                    if ($sql) {
//                        $sql = 'select * from ' . $table . ' as a left join flow_run_prcs as b on a.run_id = b.run_id left join user as c on c.user_id = b.user_id where a.run_id=' . $run_id . ' and (' . $sql . ')';
                        $sql = 'select * from ' . $table . ' as a left join flow_run_prcs as b on a.run_id = b.run_id left join user as c on c.user_id = a.begin_user where a.run_id=' . $run_id . ' and (' . $sql . ')';
                        //$sql = 'select * from flow_run_prcs as b left join user as c on b.user_id = c.user_id where b.run_id= '. $run_id . ' and (' . $sql . ') and b.prcs_id = '.$prcs_id;
//                        echo $sql, '<hr/>';
//                        die;
                        $result = M()->query($sql);

                        if ($result) {
                            $one = 1;
                        } else {
                            $one = 0;
                        }
                    }

                    if ($one) {
                        $nexts[$key]['one'] = 1;
                        $auto_type = $row['auto_type'] ? $row['auto_type'] : 0;
                        $flag ++;
                        $num = 1;
                        break;
                    } else {
                        $nexts[$key]['one'] = 0;
                    }
                } elseif ($count == 1) {
                    $nexts[$key]['one'] = 1;
                    $auto_type = $row['auto_type'] ? $row['auto_type'] : 0;
                    $flag ++;
                    $num = 1;
                } else {
                    $nexts[$key]['one'] = 1;
                    $auto_type = $row['auto_type'] ? $row['auto_type'] : 0;
                    $flag ++;
                    $num = 1;
                    //                    break;
                }
            }
        }

        if (in_array('0', $prcs_to) && $num == 0) {
            $nexts = array();
        }
//        print_r($nexts);
        //获取下一步经办人
//        $operators = $this->getData($flow_id, $row['prcs_id'], $run_id);
//        $count = count($operators);
//
//        $this->count = $count;
//        //添加步驟名和是否会签标记到$operators數組中
//        $operators = addPrcsname($operators, $flow_id, $prcs_id);

        $this->nexts = $nexts;
        $this->flag = $flag;
        $this->flow_id = $flow_id;
        $this->prcs_id = $prcs_id;
        $this->run_id = $run_id;
        $this->auto_type = $auto_type;
        $this->form_id = $runs['form_id'];
        $this->current_user = session('user_id');
        $this->display();
    }

    //获取表单值
    public function getRunData() {
        $run_id = I('run_id');
        $flow_id = I('flow_id');

        if (I('type') == 'feedback') {
            //获取会签意见
            $map['run_id'] = $run_id;
            $datas = M('flow_run_feedback')->where($map)->order('prcs_id')->select();
            foreach ($datas as $key => $row) {
                $datas[$key]['user_name'] = getChineseName($row['user_id']);
            }
        } else {
            //$data = M('flow_run_data')->where('run_id=' . $run_id)->select();
            //9.27升级后修改
            $data = M('flow_data_' . $flow_id)->where('run_id=' . $run_id)->find();
            foreach ($data as $key => $row) {
                if (strpos($key, 'data_') !== false) {
                    $datas['form'][$key] = $row; //uodate by qiaoshoujuan 20180815
                }
                if ($key == 'users') {
                    if ($row) {
                        $datas['user_ids'] = explode(',', $row);
                        foreach ($datas['user_ids'] as $k => $v) {
                            $datas['user_names'][] = getChineseName($v);
                        }
                    }
                }
            }
            //获取会签意见
            $map['run_id'] = $run_id;
            $feeds = M('flow_run_feedback')->field('user_id,prcs_id,flow_prcs,content,edit_time')->where($map)->order('prcs_id')->select();
            foreach ($feeds as $key => $row) {
                $feeds[$key]['user_name'] = getChineseName($row['user_id']);
                $pMap['flow_id'] = $flow_id;
                $pMap['prcs_id'] = $row['flow_prcs'];
                $feeds[$key]['prcs_name'] = M('flow_process')->where($pMap)->getField('prcs_name');
                $content = str_replace('<p>', ' ', $row['content']);
                $content = str_replace('</p>', ' ', $content);
                $feeds[$key]['content'] = strip_tags(htmlspecialchars($content));
            }
            $datas['feed'] = $feeds;
        }
        $datas['flow_id'] = $flow_id;   //因修改表单时flow_id手动改为0，js中动态加上，否则修改表单页面无法转交下一步
        $this->ajaxReturn($datas);
    }

    public function getFlowUser() {
        $flow_id = I('flow_id');
        $prcs_id = I('prcs_id');
        $run_id = I('run_id');
        $auto_type = I('auto_type');
        $data = $this->getData($flow_id, $prcs_id, $run_id, $auto_type);

        //添加步驟名和是否会签标记到$data數組中
        $data = addPrcsname($data, $flow_id, $prcs_id);
        foreach ($data as $key => $row) {
            $data[$key]['auto_type'] = $auto_type;
        }

        $this->ajaxReturn($data);
    }

    //发送流程催办提醒
    public function remind() {
        $data = I('get.');
        $map['run_id'] = $data['run_id'];
        $map['prcs_id'] = $data['prcs_id'];

        $flows = M('flow_run_prcs')->field('run_id,prcs_id,user_id,prcs_flag')->where($map)->select();

        if (count($flows) == 1) {
            $users = $flows[0]['user_id'];
        } else {
            foreach ($flows as $key => $row) {
                if ($row['prcs_flag'] == 1) {
                    $users[] = $row['user_id'];
                }
            }
            $users = array_unique($users);
        }
//        $users = 'zhangyingheng';
        //获取flow_id
        $run = M('flow_run')->field('run_name,flow_id,begin_user')->where('run_id=' . $data['run_id'])->find();
        $form_id = M('flow_type')->where('flow_id=' . $run['flow_id'])->getField('form_id');

        $content = "您有一条流程已逾期，\n流程名：<a href=\"http://www.jsumt.com:88/index.php/Index/Index/form/id/" . $form_id . "/run_id/" . $data['run_id'] . "/prcs_id/" . $data['prcs_id'] . "/webid/" . $this->webid . "\">" . $run['run_name'] . "，发起人：" . getChineseName($run['begin_user']) . "</a>，请尽快处理！";
//        $res = setWeixinMsg($users, $content, $this->webid);
        if ($res['errcode'] == 0) {
            $return['msg'] = '发送成功';
            $return['status'] = 1;

            //加提醒时间
            $save['remind_time'] = date('Y-m-d H:i:s');
            M('flow_run_prcs')->where($map)->save($save);

            $return['remind'] = date('Y-m-d H:i:s');
        } else {
            $return['msg'] = '发送失败';
            $return['status'] = 0;
        }
        $this->ajaxReturn($return);
    }

    public function upload() {
        $this->upfile('./Public/Uploads/flow/');
    }

    //设计表单列表
    public function formDesign() {
        $condition = I('get.');
        if ($condition['form_name']) {
            $table = 'flow_form_type';
            $where = 'form_name like "%' . $condition['form_name'] . '%"';
            $fields = 'form_id,form_name,dept_id,form_sort,fields,form_desc,edit_time';
        } elseif ($condition['flow_sort']) {
            $table = 'flow_form_type f,flow_type p,flow_sort s';
            $where = 'p.form_id = f.form_id and p.flow_sort = s.sort_id and s.sort_id = ' . $condition['flow_sort'];
            $fields = 'f.form_id,f.form_name,f.dept_id,f.form_sort,f.fields,f.form_desc,f.edit_time';
        } else {
            $table = 'flow_form_type';
            $where = '1';
            $fields = 'form_id,form_name,dept_id,form_sort,fields,form_desc,edit_time';
        }
//        echo $where;die;
        //流程分类
        $flowSorts = M('flow_sort')->where('sort_no != 0')->order('sort_no')->select();

        //获取所有表单
        $p = I('get.p', 1, 'intval');
        $limit = 20;
        $forms = M()->table($table)->field($fields)->where($where)->page($p, $limit)->select();
        $count = M()->table($table)->where($where)->count();
        $this->page = $this->pageLists($count, $limit);

//        foreach($flowSorts as $key=>$row){
//            $formids = M('flow_type')->where('flow_sort = '.$row['sort_id'])->order('flow_no')->getField('form_id',true);
//            if(!is_array($formids)){
//                $formids[] = $formids;
//            }
//            $map['form_id'] = array('in',$formids);
//            $flowSorts[$key]['forms'] = M('flow_form_type')->field('form_id,form_name,dept_id,form_sort,fields,form_desc,edit_time')->where($map)->select();
//        }
//        print_r($forms);
        $this->flowSorts = $flowSorts;
        $this->forms = $forms;
        $this->flow_id = I('flow_id');
        $this->form_id = I('form_id');
        $this->display();
    }

    //设计表单
    public function saveFormDesign() {
        if (IS_AJAX) {
            $data['form_name'] = I('form_name');
            $data['form_sort'] = I('form_sort');
            $data['dept_id'] = I('dept_id');
            $data['form_desc'] = I('form_desc');
            $data['edit_time'] = time();
            if (!I('form_id')) {
                $form_id = M('flow_form_type')->add($data);
            } else {
                $form_id = I('form_id');
            }
            if ($_POST['print_model']) {
                $design_content = trim($_POST['print_model']);  //必须用$_post，否则无法转换
                $one = M('flow_form_type')->where('form_id=' . $form_id)->find();
                import('Org.Formdesign');
                $formdesign = new \Formdesign;
                $parse_content = $formdesign->parse_form($design_content, 0);
            } elseif ($_POST['file_url']) {
                if (file_exists('./' . $_POST['file_url'])) {
                    $design_content = file_get_contents('./' . $_POST['file_url']);
                    $one = M('flow_form_type')->where('form_id=' . $form_id)->find();
                    import('Org.Formdesign');
                    $formdesign = new \Formdesign;
                    $parse_content = $formdesign->parse_form($design_content, 0, 1);
                }
            }

            if (I('form_id')) {
                //查找对应的流程数据表,修改流程数据表字段
                $ids = M('flow_type')->where('form_id=' . I('form_id'))->getField('flow_id', true); //获取flow_id,存在多条流程对应一张表单的情况
                if ($ids) {
                    if (!is_array($ids)) {
                        $ids[] = $ids;
                    }
                    foreach ($ids as $flow_id) {
                        //删除原表
//                        $sql = 'drop table flow_data_' . $flow_id;
//                        M()->execute($sql);
                        $formdesign->parse_table($flow_id, $parse_content['add_fields']);
                    }
                }
            }

            $data['fields'] = $parse_content['fields'];
            $data['print_model'] = $parse_content['template'];
            $data['print_model_short'] = $parse_content['parse'];
            $data['content_data'] = $parse_content['data'];
            $trans = M('flow_form_type')->where('form_id=' . $one['form_id'])->save($data);
            if ($trans !== false) {
                $return['status'] = 1;
                $return['url'] = U('formDesign');
            } else {
                $return['status'] = 0;
            }
            $this->ajaxReturn($return);
        }

        //获取部门
        $this->depts = M('department')->select();

        //获取分类
        $this->sorts = M('form_sort')->select();

        $this->html_editor = $html_editor;
        if (I('form_id')) {
            $info = M('flow_form_type')->where('form_id=' . I('form_id'))->find();
            if (substr($info['print_model'], 0, 1) == '?')
                $info['print_model'] = substr($info['print_model'], 1, -1);
//            $info['print_model'] = iconv('GB2312','UTF-8',$info['print_model']);
//            print_r($info['print_model']);die;
            $this->info = $info;
            $this->form_id = I('form_id');
        }

        $this->display();
    }

    //获取流程分类
    private function getFlowSort() {
        //获取流程
        $flowCates = M('flow_sort')->where('sort_no != 0')->select();

        $count = count($flowCates);
        foreach ($flowCates as $key => $row) {
            $map['flow_sort'] = $row['sort_id'];
            $map['is_delete'] = 0;
            $flowCates[$key]['child'] = M('flow_type')->field('flow_id,flow_name,form_id,icon')->where($map)->select();
            //增加隐藏流程
            $flowCates[$count] = ['sort_id' => 100, 'sort_no' => 100, 'sort_name' => '隐藏的流程'];
            $flowCates[$count]['child'] = M('flow_type')->field('flow_id,flow_name,form_id,icon')->where('is_delete = 1')->select();
        }
        return $flowCates;
    }

    //设计流程
    public function flowDesign() {
        $this->flowCates = $this->getFlowSort();
        $this->flow_id = I('flow_id');
        $this->form_id = I('form_id');
        $this->name = I('name');
        $this->display();
    }

    //预览表单
    public function formView() {
        $form_id = I('form_id');
        $one = M('flow_form_type')->where('form_id = ' . $form_id)->find();
        if (substr(trim($one['print_model']), 0, 1) == '?')
            $content = substr(trim($one['print_model']), 1, -1);  //必须用$_post，否则无法转换
        else
            $content = trim($one['print_model']);
        import('Org.Formdesign');
        $formdesign = new \Formdesign;
        $parse_content = $formdesign->parse_form($content, $one['fields']);


        $design_content = $formdesign->unparse_form(array(
            'content_parse' => $parse_content['parse'],
            'content_data' => serialize($parse_content['data']), //保存后是 serialize，所以这里也一样
                ), array(), array('action' => 'preview'));
        $this->design_content = $design_content;
        $this->display();
    }

    //删除表单
    public function delForm() {
        $form_id = I('form_id');
        //检查是否有流程表
        $ids = M('flow_type')->where('form_id=' . $form_id)->getField('flow_id', true);
        if (empty($ids)) {
            $res = M('flow_form_type')->where('form_id=' . $form_id)->delete();
            if ($res !== false) {
                $return = ['status' => 1, 'info' => '删除成功！', 'icon' => 6, 'url' => U('formDesign')];
            } else {
                $return = ['status' => 0, 'info' => '删除失败！', 'icon' => 5];
            }
        } else {
            $return = ['status' => 0, 'info' => '该表单有关联的流程，不可以删除！', 'icon' => 5];
        }
        $this->ajaxReturn($return);
    }

    //导出表单
    public function export() {
        $form_id = I('form_id');
        $form = M('flow_form_type')->where('form_id = ' . $form_id)->find();
        if ($form) {
            $form_name = $form["form_name"];
            $print_model = $form["print_model"];
            $script = $form["script"];
            $css = $form["css"];
        }

        $letter_str = "\\,/,:,*,?,\",<,>,|";
        $my_array = explode(",", $letter_str);
        $array_count = sizeof($my_array);
        if ($my_array[$array_count - 1] == "")
            $array_count--;
        for ($i = 0; $i < $array_count; $i++) {
            $form_name = str_replace($my_array[$i], "", $form_name);
        }

        header("Cache-control: private");
        Header("Content-type: text/plain");
        Header("Accept-Ranges: bytes");
        Header("Accept-Length: " . strlen($print_model));
        Header("Content-Disposition: attachment; filename=" . $form_name . ".html");

        echo $print_model;
    }

    //add/edit for flow attribute
    public function newFlow() {
        if (IS_AJAX) {
            $data = I('post.');
//            $data = array_change_key_case($data, CASE_UPPER);
            $data['icon'] = I('icon') ? I('icon') : 'e621';
            $data['color'] = I('color');
            $data['uploads'] = I('uploads');
            $data['uploads_url'] = I('uploads_url');

            $flag = true;
            if (I('flow_id')) {
                //edit
                $map['flow_id'] = I('flow_id');
                $res = M('flow_type')->where($map)->save($data);
                $flow_id = I('flow_id');
            } else {
                //add
                $data['flow_action'] = '1,2,3,4,';
                //去重
                $map['flow_name'] = I('flow_name');
                $map['form_id'] = I('form_id');
                $one = M('flow_type')->where($map)->find();
                if (!$one) {
                    $res = M('flow_type')->add($data);
                    $flow_id = $res;

                    //创建该流程数据表flow_data_(flow_id)
                    $form = M('flow_form_type')->where('form_id=' . I('form_id'))->find();
                    import('Org.Formdesign');
                    $formdesign = new \Formdesign;
                    $parse_content = $formdesign->parse_form($form['print_model'], 0);
                    $formdesign->parse_table($flow_id, $parse_content['add_fields']);
                } else {
                    $flag = false;
                    $flow_id = $one['flow_id'];
                }
            }

            if ($flag == true) {
                if ($res !== false) {
                    $return = array('info' => '提交成功', 'status' => 1, 'icon' => 6, 'url' => U('flowDesign', array('flow_id' => $flow_id)));
                } else {
                    $return = array('info' => '提交失败', 'status' => 0, 'icon' => 5);
                }
            } else {
                $return = array('info' => '请勿重复提交', 'status' => 0, 'icon' => 5, 'url' => U('flowDesign', array('flow_id' => $flow_id)));
            }

            $this->ajaxReturn($return);
        }

        $flow_id = I('flow_id');

        if ($flow_id) {
            $this->info = M('flow_type')->where('flow_id=' . $flow_id)->find();
        }
        //获取表单
        $this->forms = M('flow_form_type')->field('form_id,form_name,dept_id,form_sort')->select();

        $this->flow_id = $flow_id;
        if ($flow_id) {
            $this->form_id = M('flow_type')->where('flow_id=' . $flow_id)->getField('form_id');
        }

        $this->display();
    }

    //design flow step
    public function flowStep() {
        //get flow process
        $process = M('flow_process')->field('flow_id,prcs_id,prcs_name,prcs_to')->where('flow_id=' . I('flow_id'))->order('prcs_id asc, id desc')->select();
        foreach ($process as $key => $row) {
            $process[$key]['prcs_to'] = str_replace('0', '结束', $row['prcs_to']);  //replace 0 -> end
        }
        $this->flow_id = I('flow_id');
        $this->form_id = M('flow_type')->where('flow_id=' . I('flow_id'))->getField('form_id');
        $this->process = $process;
        $this->display();
    }

    //create or eidt flow basic attribute
    public function newFlowStep() {
        if (IS_AJAX) {
            $data = I('post.');
            unset($data['prcs_to']);
            if (I('prcs_to')[0]) {
                foreach (I('prcs_to') as $row) {
                    if ($row == 'end') {
                        $row = '0';
                    }
                    if (!empty($row) || $row === '0') {
                        $data['prcs_to'] .= $row . ',';
                    }
                }
            } else {
                $data['prcs_to'] = '';
            }

            //默认主办人
            $data['auto_user_op'] = $data['user_id'];
            //经办人
            $data['auto_user'] = implode(',', $data['user_ids']);
            //默认角色
            $data['auto_prive'] = implode(',', $data['auto_prive']);

//            $data = array_change_key_case($data, CASE_UPPER);

            $map['flow_id'] = $data['flow_id'];
//            $map['prcs_id'] = $data['prcs_id'];
            $map['prcs_name'] = $data['prcs_name'];
            $row = M('flow_process')->where($map)->find();
            if ($row) {
                //edit
                $res = M('flow_process')->where($map)->save($data);
            } else {
                //add
                $res = M('flow_process')->add($data);
            }

            if ($res !== FALSE) {
                $return = array('status' => 1, 'info' => '提交成功', 'icon' => 6, 'url' => U('Flow/flowStep', array('flow_id' => $data['flow_id'])));
            } else {
                $return = array('status' => 0, 'info' => '提交失败', 'icon' => 5);
            }
            $this->ajaxReturn($return);
        }

        if (I('prcs_id')) {
            $map['flow_id'] = I('flow_id');
            $map['prcs_id'] = I('prcs_id');     //current flow step number
            $info = M('flow_process')->where($map)->find();   //get current flow step message
            //current flow all step
            unset($map['prcs_id']);
            $steps = M('flow_process')->field('id,flow_id,prcs_id,prcs_name')->where($map)->order('prcs_id')->select();
            if ($info['prcs_to']) {
                //get next step name
                $info['nextSteps'] = explode(',', rtrim($info['prcs_to'], ','));
                foreach ($info['nextSteps'] as $key => $row) {
                    if ($row == 0) {
                        $info['nextSteps'][$key] = 'end';
                        $is_end = 1;    //是否结束标记，当前步骤有最后一步，备选步骤中不出现结束
                    }
                }
                foreach ($steps as $key => $row) {
                    //delete exist step
                    if (!in_array($row['prcs_id'], $info['nextSteps'])) {
                        $newSteps[] = $row;
                    }
                }
            } else {
                $info['nextSteps'] = '';
            }

            if ($info['auto_user']) {
                $info['users'] = explode(',', rtrim($info['auto_user']));
            }
            if ($info['auto_prive']) {
                $info['prives'] = explode(',', rtrim($info['auto_prive']));
            }
//print_r($info);
            $this->info = $info;
        } else {
            $map['flow_id'] = I('flow_id');
            $newSteps = M('flow_process')->field('id,flow_id,prcs_id,prcs_name')->where($map)->order('prcs_id')->select();
        }

        $this->steps = $newSteps ? $newSteps : $steps;
        $this->is_end = $is_end ? 1 : 0;
        $this->prcs = I('prcs_id');
        $this->flow_id = I('flow_id');
        $this->display();
    }

    //结束流程
    public function overFlow() {
        $data = I('post.');
        //修改prcs表状态=4
        $map['run_id'] = $data['run_id'];
        $map['flow_prcs'] = $data['over_prcs_id'];
        $sdata['prcs_flag'] = 4;
        $sdata['deliver_time'] = date('Y-m-d H:i:s');
        $res = M('flow_run_prcs')->where($map)->save($sdata);

        if ($res !== false) {
            //增加flow_run表end_time字段
            $rMap['run_id'] = $data['run_id'];
            $rData['end_time'] = date('Y-m-d H:i:s');
            M('flow_run')->where($rMap)->save($rData);

            //添加日志
            unset($sdata);
            $map['user_id'] = session('user_id');
            $row = M('flow_run_prcs')->where($map)->find();
            $sdata['run_id'] = $data['run_id'];
            $sdata['flow_id'] = $data['flow_id'];
            $sdata['run_name'] = M('flow_form_type')->where(array('form_id' => $data['form_id']))->getField('form_name') . '(' . date('Y-m-d H:i:s') . ')';
            $sdata['prcs_id'] = $row['prcs_id'];
            $sdata['flow_prcs'] = $row['flow_prcs'];
            $sdata['user_id'] = $row['user_id'];
            $sdata['time'] = date('Y-m-d H:i:s');
            $sdata['ip'] = gethostbyname($_ENV['COMPUTERNAME']);
            $sdata['type'] = 1;
            $sdata['content'] = '结束流程';
            M('flow_run_log')->add($sdata);

            //修改当前步骤其他用户日志
            unset($map);
            unset($sdata);
            $map['run_id'] = $data['run_id'];
            $map['flow_prcs'] = $row['flow_prcs'];
            $map['flow_id'] = $data['flow_id'];
            $sdata['content'] = '结束流程';
            $res = M('flow_run_log')->where($map)->save($sdata);
        }

        $return['url'] = $res !== false ? U('Flow/lists', array('type' => 2)) : '';
        $return['info'] = $res !== false ? '流程办理成功' : '流程办理失败';
        $this->ajaxReturn($return);
    }

    //ajax获取流程名
    public function getFlowName() {
        $flow_id = I('flow_id');
        $this->ajaxReturn(M('flow_type')->where('flow_id=' . $flow_id)->getField('flow_name'));
    }

    //隐藏流程
    public function flowHide() {
        $flow_id = I('flow_id');
        //hide flow step => flow_process
        $map['flow_id'] = $flow_id;
        $data['is_delete'] = 1;
        $res = M('flow_type')->where($map)->save($data);
        if ($res !== false) {
            $return = array('status' => 1, 'info' => '操作成功', 'icon' => 6, 'url' => U('FlowDesign'));
        } else {
            $return = array('status' => 0, 'icon' => 5, 'info' => '操作失败');
        }
        $this->ajaxReturn($return);
    }

    //显示流程
    public function flowShow() {
        $flow_id = I('flow_id');
        //show flow step => flow_process
        $map['flow_id'] = $flow_id;
        $data['is_delete'] = 0;
        $res = M('flow_type')->where($map)->save($data);
        if ($res !== false) {
            $return = array('status' => 1, 'info' => '操作成功', 'icon' => 6, 'url' => U('FlowDesign'));
        } else {
            $return = array('status' => 0, 'icon' => 5, 'info' => '操作失败');
        }
        $this->ajaxReturn($return);
    }

    //delete flow and all data
    public function flowDelete() {
        $flow_id = I('flow_id');

        //取flow_type表的数据
        $row = M('flow_type')->where('flow_id=' . $flow_id)->find();
        if ($row['uploads_url']) {    //delete flow_type files
            $urls = explode(',', rtrim($row['uploads_url'], ','));
            foreach ($urls as $url) {
                @unlink('.' . $url);
            }
        }

        //删除flow_process
        $proRes = M('flow_process')->where('flow_id=' . $flow_id)->delete();

        //find flow_run table all run_id
        $runIds = M('flow_run')->where('flow_id=' . $flow_id)->getField('run_id', true);
        if (!is_array($runIds)) {
            $runIds[] = $runIds;
        }
        //delete flow_run all files
        $uploads = M('flow_run')->where('flow_id=' . $flow_id)->getField('uploads_url', true);
        foreach ($uploads as $key => $url) {
            $urls = explode(',', rtrim($url, ','));
            foreach ($urls as $one) {
                @unlink('.' . $one);
            }
        }

        //delete flow_run_prcs
        $map['run_id'] = array('in', $runIds);
        $prcsRes = M('flow_run_prcs')->where($map)->delete();

        //delete flow_run_log
        $logRes = M('flow_run_log')->where($map)->delete();

        //delete flow_run_feedback
        $feedRes = M('flow_run_feedback')->where($map)->delete();

        //delete flow_run
        $runRes = M('flow_run')->where($map)->delete();

        //delete flow_data_(flow_id)
        $sql = 'drop table flow_data_' . $flow_id;
        $dataRes = M()->execute($sql);

        //delete flow_type
        $flowRes = M('flow_type')->where('flow_id=' . $flow_id)->delete();

        if ($proRes !== false && $prcsRes !== false && $logRes !== false && $feedRes !== false && $runRes !== false && $dataRes >= 0 && $flowRes !== false) {
            $return = ['status' => 1, 'info' => '删除成功', 'icon' => 6, 'url' => U('flowDesign')];
        } else {
            $return = ['status' => 0, 'info' => '删除失败', 'icon' => 5];
        }
        $this->ajaxReturn($return);
    }

    //经办权限
    public function flowPower() {
        if (IS_AJAX) {
            $data = I('post.');
            $data['prcs_user'] = $data['user_ids'] ? implode(',', $data['user_ids']) : '';
            $data['prcs_dept'] = $data['prcs_dept'] ? implode(',', $data['prcs_dept']) : '';
            $data['prcs_priv'] = $data['prcs_priv'] ? implode(',', $data['prcs_priv']) : '';
//            $data = array_change_key_case($data, CASE_UPPER);
            $map['flow_id'] = I('pro_flow_id');
            $map['prcs_id'] = I('prcs_id');

            $res = M('flow_process')->where($map)->save($data);

            if ($res !== FALSE) {
                $return = array('status' => 1, 'info' => '保存成功', 'icon' => 6, 'url' => U('flowStep', array('flow_id' => I('pro_flow_id'))));
            } else {
                $return = array('status' => 0, 'info' => '保存失败', 'icon' => 5);
            }

            $this->ajaxReturn($return);
        }

        if (I('prcs_id')) {
            $map['flow_id'] = I('flow_id');
            $map['prcs_id'] = I('prcs_id');     //current flow step number
            $info = M('flow_process')->where($map)->find();

            $this->info = $info;
        }

        //获取当前步骤信息
        $map['flow_id'] = I('flow_id');
        $map['prcs_id'] = I('prcs_id');
        $process = M('flow_process')->where($map)->find();
        if ($process['prcs_user']) {
            $process['users'] = explode(',', rtrim($process['prcs_user'], ','));
        }
        if ($process['prcs_dept']) {
            $process['depts'] = explode(',', rtrim($process['prcs_dept'], ','));
        }
        if ($process['prcs_priv']) {
            $process['privs'] = explode(',', rtrim($process['prcs_priv'], ','));
        }
//        print_r($process);

        $this->info = $process;
        $this->prcs_id = I('prcs_id');
        $this->flow_id = I('flow_id');
        $this->display();
    }

    //可写字段
    public function flowField() {
        if (IS_AJAX) {
//            $data = I('post.');
            foreach (I('prcs_item') as $row) {
                if ($row) {
                    $data['prcs_item'] .= $row . ',';
                }
            }
            foreach (I('prcs_item_auto') as $row) {
                if ($row) {
                    $data['prcs_item_auto'] .= $row . ',';
                }
            }
            $data['attach_edit_priv'] = I('attach_edit_priv');
            $map['flow_id'] = I('flow_id');
            $map['prcs_id'] = I('prcs_id');
            $res = M('flow_process')->where($map)->save($data);
            if ($res !== false) {
                $return = array('info' => '保存成功', 'icon' => 6, 'status' => 1, 'url' => U('flowStep', array('flow_id' => I('flow_id'))));
            } else {
                $return = array('info' => '保存失败', 'icon' => 5, 'status' => 0);
            }
            $this->ajaxReturn($return);
        }

        //获取form_id
        $htmlTitle = $this->getFormNameTitle(I('flow_id'));
        $this->titles = $htmlTitle;

        //获取当前步骤信息
        $map['flow_id'] = I('flow_id');
        $map['prcs_id'] = I('prcs_id');
        $process = M('flow_process')->where($map)->find();

        //获取可写字段和自动赋值字段
        if ($process['prcs_item']) {
            $process['prcs_item'] = explode(',', rtrim($process['prcs_item'], ','));
        }
        if ($process['prcs_item_auto']) {
            $process['prcs_item_auto'] = explode(',', rtrim($process['prcs_item_auto'], ','));
        }

        $this->info = $process;
        $this->prcs_id = I('prcs_id');
        $this->flow_id = I('flow_id');
        $this->display();
    }

    //flow condition page
    public function flowCondition() {
        if (IS_AJAX) {
//            $data = I('post.');
            $data = $_POST;
            if ($data['prcs_in']) {
                foreach ($data['prcs_in'] as $key => $row) {
                    $data['prcs_in'][$key] = filterFieldEncode($row);
                }
                $data['prcs_in'] = implode("\n", $data['prcs_in']);
            } else {
                $data['prcs_in'] = '';
            }
            if ($data['prcs_out']) {
                foreach ($data['prcs_out'] as $key => $row) {
                    $data['prcs_out'][$key] = filterFieldEncode($row);
                }
                $data['prcs_out'] = implode("\n", $data['prcs_out']);
            } else {
                $data['prcs_out'] = '';
            }
//            $data = array_change_key_case($data, CASE_UPPER);
            $map['flow_id'] = I('flow_id');
            $map['prcs_id'] = I('prcs_id');
            $res = M('flow_process')->where($map)->save($data);
            if ($res !== false) {
                $return = array('status' => 1, 'info' => '保存成功', 'icon' => 6, 'url' => U('flowStep', array('flow_id' => I('flow_id'))));
            } else {
                $return = array('status' => 0, 'info' => '保存失败', 'icon' => 5);
            }

            $this->ajaxReturn($return);
        }
        $htmlTitle = $this->getFormNameTitle(I('flow_id'));
        $this->titles = $htmlTitle;

        //获取当前步骤信息
        $map['flow_id'] = I('flow_id');
        $map['prcs_id'] = I('prcs_id');
        $info = M('flow_process')->where($map)->find();
//        print_r($info);
        //获取当前步骤转入条件
        if ($info['prcs_in']) {
            $info['prcs_in'] = str_replace("\n", "<br>", $info['prcs_in']);
            $info['prcs_in'] = explode('<br>', trim($info['prcs_in'], '<br>'));
        }
        //获取当前步骤转出条件
        if ($info['prcs_out']) {
            $info['prcs_out'] = str_replace("\n", "<br>", $info['prcs_out']);
            $info['prcs_out'] = explode('<br>', trim($info['prcs_out'], '<br>'));
        }

//        print_r($info);
        $this->info = $info;
        $this->flow_id = I('flow_id');
        $this->prcs_id = I('prcs_id');
        $this->display();
    }

    /* 获取表单中的name和title
     * param $flow_id   流程id
     * param $type      获取类型(默认获取title)  0:title   1:name  2:获取name和title
     * return array
     */

    private function getFormNameTitle($flow_id, $type = 0) {
        //获取form_id
        $form_id = M('flow_type')->where('flow_id=' . $flow_id)->getField('form_id');
        $html = M('flow_form_type')->where('form_id=' . $form_id)->getField('print_model');
        preg_match_all('/title[\s]*?=[\s]*?([\'\"])(.*?)\1/', $html, $match);
        $htmlTitle = $match[2];     //获取表单中的title
        preg_match_all('/[^s]name[\s]*?=[\s]*?([\'\"])(.*?)\1/', $html, $match);
        $htmlName = $match[2];  //获取表单中的Name

        if (!$type) {
            //title
            $array = $htmlTitle;
        } else {
            if ($type == 1) {
                //name
                $array = $htmlName;
            } else {
                $array['title'] = $htmlTitle;
                $array['name'] = $htmlname;
            }
        }
        return $array;
    }

    //delete flow step
    public function deleteStep() {
        $flow_id = I('flow_id');
        $prcs_id = I('prcs_id');
        $map['flow_id'] = I('flow_id');
        $map['prcs_id'] = I('prcs_id');

        $res = M('flow_process')->where($map)->delete();
        if ($res !== false) {
            $return = array('status' => 1, 'info' => '删除成功', 'icon' => 6, 'url' => U('flowStep', array('flow_id' => $flow_id)));
        } else {
            $return = array('status' => 0, 'info' => '删除失败', 'icon' => 5);
        }
        $this->ajaxReturn($return);
    }

    //增加管理权限
    public function flowPriv() {
        $data['priv_type'] = I('priv_type');
        $data['priv_scope'] = I('priv_scope');
        $data['user'] = I('user_ids')[0] ? implode(',', I('user_ids')) : '';
        $data['dept'] = I('dept')[0] ? implode(',', I('dept')) : '';
        $data['role'] = I('role')[0] ? implode(',', I('role')) : '';
        $data['flow_id'] = I('pro_flow_id');

        $flag = true;
        if (I('id')) {
            $map['id'] = I('id');
            $res = M('flow_priv')->where($map)->save($data);
            $id = I('id');
        } else {
            $map['flow_id'] = I('pro_flow_id');
            $map['priv_type'] = I('priv_type');
            $count = M('flow_priv')->where($map)->count();
            if (!$count) {
                $res = M('flow_priv')->add($data);
                $id = $res;
            } else {
                $return = ['status' => 0, 'info' => '请勿重复提交', 'icon' => 5];
                $flag = false;
            }
        }

        if ($flag) {
            if ($res !== false) {
                if (I('id')) {
                    $return = ['status' => 1, 'edit' => 1, 'url' => U('Flow/getFlowPriv', array('id' => $id, 'flow_id' => I('pro_flow_id')))];   //修改：在原数据上改
                } else {
                    $return = ['status' => 1, 'url' => U('Flow/getFlowPriv', array('id' => $id, 'flow_id' => I('pro_flow_id')))]; //新建：增加一条
                }
            } else {
                $return = ['status' => 0, 'info' => '提交失败', 'icon' => 5];
            }
        }
        $this->ajaxReturn($return);
    }

    //获取单个流程的管理权限
    public function getFlowPriv() {
        $id = I('id');
        $type = I('type');
        $flow_id = I('get.flow_id');
        $form_id = M('flow_type')->where('flow_id=' . $flow_id)->getField('form_id');
        if ($type) {
            $map['flow_id'] = $flow_id;
            $privs['data'] = M('flow_priv')->where($map)->select();
            foreach ($privs['data'] as $key => $row) {
                $privs['data'][$key]['priv_type'] = getFlowPrivTypeName($row['priv_type']);
                $privs['data'][$key]['priv_scope'] = getFlowPrivScopeName($row['priv_scope']);
                $privs['data'][$key]['user'] = $row['user'] ? getMoreUsername($row['user']) : '';
                $privs['data'][$key]['dept'] = $row['dept'] ? getMoreDeptname($row['dept']) : '';
                $privs['data'][$key]['role'] = $row['role'] ? getMorePrivname($row['role']) : '';
                $privs['data'][$key]['form_id'] = $form_id;
            }
            $privs['form_id'] = $form_id;
        } else {
            $privs = M('flow_priv')->find($id);
            $privs['priv_type'] = getFlowPrivTypeName($privs['priv_type']);
            $privs['priv_scope'] = getFlowPrivScopeName($privs['priv_scope']);
            $privs['user'] = $privs['user'] ? getMoreUsername($privs['user']) : '';
            $privs['dept'] = $privs['dept'] ? getMoreDeptname($privs['dept']) : '';
            $privs['role'] = $privs['role'] ? getMorePrivname($privs['role']) : '';
            $privs['form_id'] = $form_id;
        }

        $this->ajaxReturn($privs);
    }

    //删除流程授权项
    public function delFlowPriv() {
        $res = M('flow_priv')->delete(I('id'));
        if ($res !== false) {
            $return = ['status' => 1, 'info' => '删除成功', 'icon' => 6];
        } else {
            $return = ['status' => 0, 'info' => '删除失败', 'icon' => 5];
        }
        $this->ajaxReturn($return);
    }

    //修改条件
    public function saveCondition() {
        $map['flow_id'] = I('flow_id');
        $map['prcs_id'] = I('prcs_id');

        $data = $_POST;
        if ($data['prcs_in']) {
            foreach ($data['prcs_in'] as $key => $row) {
                $data['prcs_in'][$key] = filterFieldEncode($row);
            }
            $data['prcs_in'] = implode("\n", $data['prcs_in']);
        }
        if ($data['prcs_out']) {
            foreach ($data['prcs_out'] as $key => $row) {
                $data['prcs_out'][$key] = filterFieldEncode($row);
            }
            $data['prcs_out'] = implode("\n", $data['prcs_out']);
        }
//        $data = array_change_key_case($data, CASE_UPPER);
        M('flow_process')->where($map)->save($data);
    }

    //重走流程
    public function repeatFlow() {
        $run_id = I('run_id');
        $map['run_id'] = $run_id;
        $map['prcs_id'] = array('neq', 1);
        $dres = M('flow_run_prcs')->where($map)->delete();
        $dres = M('flow_run_log')->where($map)->delete();

        $map['prcs_id'] = 1;
        $data['prcs_flag'] = 2;
        $data['deliver_time'] = '0000-00-00';
        $sres = M('flow_run_prcs')->where($map)->save($data);

        unset($data);
        $data['content'] = '';
        $dres = M('flow_run_log')->where($map)->save($data);

        unset($map['prcs_id']);
        unset($data);
        $data['focus_user'] = '';
        $data['end_time'] = '';
        $data['focus_over'] = '';   //强制结束信息
        $runRes = M('flow_run')->where($map)->save($data);

        if ($dres !== false && $sres !== false) {
            $return = ['status' => 1, 'info' => '操作成功', 'icon' => 6, 'reload' => 1];
        } else {
            $return = ['status' => 0, 'info' => '操作失败', 'icon' => 5];
        }
        $this->ajaxReturn($return);
    }

    //强制结束
    public function endFlow() {
        $map['run_id'] = I('run_id');
        $data['focus_user'] = session('user_id');
        $data['end_time'] = date('Y-m-d H:i:s');
        $data['focus_over'] = '';   //强制结束信息
        $runRes = M('flow_run')->where($map)->save($data);

        //修改flow_run_prcs表
        unset($data);
        $data['prcs_flag'] = 4;
        $data['deliver_time'] = date('Y-m-d H:i:s');
        $prcsRes = M('flow_run_prcs')->where($map)->save($data);

        //修改flow_run_log表
        unset($data);
        $data['content'] = '结束流程';
        $map['prcs_id'] = M('flow_run_log')->where($map)->max('prcs_id');
        $logRes = M('flow_run_log')->where($map)->save($data);

        if ($runRes !== false && $prcsRes !== false) {
            $return = ['status' => 1, 'info' => '操作成功', 'icon' => 6, 'reload' => 1];
        } else {
            $return = ['status' => 0, 'info' => '操作失败', 'icon' => 5];
        }
        $this->ajaxReturn($return);
    }

    //强制删除
    public function delFlow() {
        $map['run_id'] = I('run_id');
        $data['del_flag'] = 1;
        $res = M('flow_run')->where($map)->save($data);

        if ($res !== false) {
            $return = ['status' => 1, 'info' => '操作成功', 'icon' => 6, 'reload' => 1];
        } else {
            $return = ['status' => 0, 'info' => '操作失败', 'icon' => 5];
        }
        $this->ajaxReturn($return);
    }

    //设置分类
    public function setCate() {
        if (IS_AJAX) {
            $data = I('post.');
            $table = $data['ctrl'] == 'flow' ? 'flow_sort' : 'form_sort';
            if ($data['id']) {
                $map['sort_id'] = $data['id'];
                $res = M($table)->where($map)->save($data);
            } else {
                $map['sort_name'] = $data['sort_name'];
                $row = M($table)->where($map)->count();
                if (!$row) {
                    $res = M($table)->add($data);
                } else {
                    $return = ['info' => '请勿重复操作', 'icon' => 5, 'status' => 0];
                }
            }

            if ($res !== false) {
                $return = ['info' => '操作成功', 'icon' => 6, 'parent' => 1, 'status' => 1];
            } else {
                $return = ['info' => '操作失败', 'icon' => 5, 'status' => 0];
            }
            $this->ajaxReturn($return);
        }
        //获取流程分类
        $this->flowCates = M('flow_sort')->order('sort_no')->select();
        $this->flowCount = count($this->flowCates);

        //获取表单分类
        $this->formCates = M('form_sort')->order('sort_no')->select();
        $this->formCount = count($this->formCates);
        $this->display();
    }

    //回退
    public function backFlow() {
        $data = I('get.');

        //获取上一步信息并修改状态
        $prveMap['run_id'] = $data['run_id'];
        $prveMap['prcs_id'] = $data['current_prcs_id'] - 1;
        $prveData['prcs_flag'] = 4;
        M('flow_run_prcs')->where($prveMap)->save($prveData);

        //获取回退的步骤信息
        $map['run_id'] = $data['run_id'];
        $map['flow_prcs'] = $data['flow_prcs'];
        $row = M('flow_run_prcs')->where($map)->find();

        //添加flow_run_prcs表
        $fData['run_id'] = $data['run_id'];
        $fData['prcs_id'] = $data['current_prcs_id'] + 1;
        $fData['user_id'] = $row['user_id'];
        $fData['prcs_time'] = date('Y-m-d H:i:s');
        $fData['prcs_flag'] = 1;
        $fData['flow_prcs'] = $row['flow_prcs'];
        $fData['op_flag'] = $row['op_flag'];
        $fData['top_flag'] = $row['top_flag'];
        $fData['create_time'] = date('Y-m-d H:i:s');
        $fData['prcs_dept'] = $row['prcs_dept'];
        $fData['parent'] = $data['current_flow_prcs'];
        $fData['parent_prcs_id'] = $data['current_prcs_id'];
        $fData['is_mobile'] = 1;
        $fRes = M('flow_run_prcs')->add($fData);

        //修改flow_run_prcs当前步骤
        unset($map);
        $map['run_id'] = $data['run_id'];
        $map['prcs_id'] = $data['current_prcs_id'];     //当前流程标识(唯一)
        $sData['deliver_time'] = date('Y-m-d H:i:s');
        $sData['back_prcs_id'] = $data['prcs_id'];
        $sData['back_flow_prcs'] = $data['flow_prcs'];
        $sData['prcs_flag'] = 0;
        $sData['mobile_flag'] = 1;
        $fsRes = M('flow_run_prcs')->where($map)->save($sData);

        //添加flow_run_log表
        $run = M('flow_run')->where(array('RUN_ID' => $data['run_id']))->find();
        $lData['run_id'] = $data['run_id'];
        $lData['run_name'] = $run['run_name'];
        $lData['flow_id'] = $run['flow_id'];
        $lData['prcs_id'] = $data['current_prcs_id'] + 1;
        $lData['flow_prcs'] = $row['flow_prcs'];
        $lData['user_id'] = $row['user_id'];
        $lData['time'] = date('Y-m-d H:i:s');
        $lData['ip'] = gethostbyname($_ENV['COMPUTERNAME']);
        $lData['type'] = 1;
        $lRes = M('flow_run_log')->add($lData);

        //修改当前步骤log
        unset($map);
        unset($sData);
        $map['RUN_ID'] = $data['run_id'];
        $map['PRCS_ID'] = $data['current_prcs_id'];
        $sData['CONTENT'] = '回退到第' . $data['prcs_id'] . '步';
        $lsRes = M('flow_run_log')->where($map)->save($sData);

        if ($fRes) {
            $return['info'] = '回退成功';
            $return['url'] = U('Flow/lists', array('type' => 2));

            //发送退回提醒
            $form = M('flow_type')->where('FLOW_ID=' . $run['flow_id'])->find();
            //发起人
            $creator = M('flow_run_prcs')->where(array('RUN_ID' => $row['run_id'], 'FLOW_PRCS' => 1))->getField('user_id');
            $currPrcs = $data['current_prcs_id'] + 1;
            $content = "您有一条流程被退回，请尽快办理，\n流程名：<a href=\"http://www.jsumt.com:88/index.php/Index/Index/form/id/" . $form['form_id'] . "/run_id/" . $data['run_id'] . "/prcs_id/" . $currPrcs . "/webid/" . $this->webid . "\">" . $run['run_name'] . "，发起人：" . getChineseName($creator) . "</a>，转交人：" . getChineseName(session('user_id'));
//            setWeixinMsg($row['user_id'], $content, $this->webid);

            /*
             * 修改和考勤相关的数据
             * 删除请假表记录
             */
            $flow_id = M('flow_run')->where('RUN_ID=' . $data['run_id'])->getField('flow_id');

            $where['_string'] = ' FLOW_NAME like "请假申请%" or FLOW_NAME like "出差申请%" or FLOW_NAME like "外出申请%" or FLOW_NAME like "加班申请%"';
            $flow_ids = M('flow_type')->where($where)->getField('flow_id', true);

            if ($data['flow_prcs'] == 1) {  //回退到第一步时判断
                switch ($flow_id) {
                    case 146:       //请假流程 
                        // 获取表单数据
                        $flow_data = M('flow_data_' . $flow_id)->where('RUN_ID=' . $data['run_id'])->find();
                        switch ($flow_data['data_35']) {
                            case '年假':
                                $ableYear = M('userinfo')->where('user_id="' . $flow_data['begin_user'] . '"')->getField('able_year');
                                $infoData['able_year'] = $ableYear + floatval($flow_data['data_66']);
                                break;
                            case '调休':
                                $ableVacation = M('userinfo')->where('user_id="' . $flow_data['begin_user'] . '"')->getField('able_vacation');
                                $infoData['able_vacation'] = $ableVacation + floatval($flow_data['data_66']);
                                break;
                        }

                        $countNum = M('attend_leave')->where('RUN_ID=' . $data['run_id'])->count();
                        if ($countNum > 0) {    //如果该流程id存在，则删除
                            $infoMap['user_id'] = $flow_data['begin_user'];
                            M('userinfo')->where($infoMap)->save($infoData);
                            M('attend_leave')->where('RUN_ID=' . $data['run_id'])->delete();
                        }
                        break;
                    case 163:   //外出
                        $countNum = M('attend_out')->where('RUN_ID=' . $data['run_id'])->count();
                        if ($countNum > 0) {
                            M('attend_out')->where('RUN_ID=' . $data['run_id'])->delete();
                        }
                        break;
                    case 150:       //出差
                        $countNum = M('attend_evection')->where('RUN_ID=' . $data['run_id'])->count();
                        if ($countNum > 0) {
                            M('attend_evection')->where('RUN_ID=' . $data['run_id'])->delete();
                        }
                        break;
                    case 145:       //加班
                        $countNum = M('attendance_overtime')->where('RUN_ID=' . $data['run_id'])->count();
                        if ($countNum > 0) {
                            M('attendance_overtime')->where('RUN_ID=' . $data['run_id'])->delete();
                        }
                        //减少调休
                        $flow_data = M('flow_data_' . $flow_id)->where('RUN_ID=' . $data['run_id'])->find();
                        $ableVacation = M('userinfo')->where('user_id="' . $flow_data['begin_user'] . '"')->getField('able_vacation');
                        $overtime = floatval($flow_data['data_60']) / 8;
                        $infoData['able_vacation'] = $ableVacation - substr(sprintf("%.4f", $overtime), 0, -1);
                        $infoMap['user_id'] = $flow_data['begin_user'];
                        M('userinfo')->where($infoMap)->save($infoData);
                        break;
                }
            }
        } else {
            $return['info'] = '回退失败';
        }
//        var_dump($resturn);
        $this->ajaxReturn($return);
    }

}
